this

클래스인 객체 자신을 지칭하는 명령어

 


this의 종류

  • this.변수 - 자기 자신의 변수 호출
  • this.메서드() - 자기 자신의 메서드 호출
  • this() - 자기 자신의 생성자 호출

※ this는 static 메서드 안에서 사용할 수 없다.


this의 규칙

  • static 메서드, 메인 메서드 내에서 사용할 수 없다.
  • 생성사 호출시 this( )생성자 코드의 첫 줄에만 작성할 수 있다.

[예제1- this.변수, this.메서드()]

package day06;

public class CoffeeMachine {
    int coffee;
    int sugar;
    int cream;
	
    //1번 메서드
    public String makeTea(int coffee){
        this.coffee = coffee; //this.변수 - 자기 자신의 변수 호출
        return "블랙커피 나가요~~ 농도: " + this.coffee;
    }
    //2번 메서드
    public void makeTea(int coffee, short sugar){
        this.coffee = coffee;
        this.sugar = sugar;
        System.out.println("설탕커피 나가요~~ 농도: " + (this.coffee + this.sugar));
        System.out.println("2번 메서드 사용");
    }
    //3번 메서드
    public void makeTea(short sugar, int coffee){
        this.makeTea(coffee, sugar); //this.메서드(매개변수) - 자기 자신의 메서드(입력값) 호출
        //2번 메서드를 사용한다.
        System.out.println("3번 메서드 사용");
    }
}
package day06;

public class Cafe {
    public static void main(String[] args) {
        CoffeeMachine cm = new CoffeeMachine();
        System.out.println(cm.makeTea(10));
        cm.makeTea(5, (short)2);
        cm.makeTea((short)1, 2);
    }
}

실행 결과

 


[예제2- this(): 생성자 호출]

package day07;

public class Demo2_Superman {
	String name;//이름
	int height;//키
	int power;//초능력
	//this(): 생성자 안에서 첫 번째 라인에서 호출 가능. 다른 생성자를 부르는 일종의 메서드
	
	//생성자1(기본생성자) - 기본생성자는 매개변수가 없음, setter 역할
	public Demo2_Superman() {
		this("슈퍼맨", 155, 100); //생성자4 호출
	}//--------------------
	//생성자2
	public Demo2_Superman(String name) { //인자 생성자 => 생성자 오버로딩(다중정의)
		this(name, 160, 200); //생성자4 호출
	}
	//생성자3
	public Demo2_Superman(String name, int height) {
		this(name, height, 300); //생성자4 호출
	}
	//생성자4-target
	public Demo2_Superman(String name, int height, int power) {
		this.name = name;
		this.height = height;
		this.power = power;
	}
	//메서드
	public void showInfo() {
		System.out.println("이름: " + name);
		System.out.println("키: " + height);
		System.out.println("초능력: " + power);
	}
}

생성자1, 2, 3에서 this()를 통해 생성자4를 호출해서 사용하고 있다.

+ Recent posts