Java에서 this는 인스턴스, 자기 자신을 가리키는 키워드다.
this를 통해 클래스 메소드 및 생성자에서 자기 자신의 데이터를 업데이트 or 조작할 수 있다.
this는 클래스를 기반으로 생성된 인스턴스를 가리키는 참조라는 것이다.
여기서 중요한 부분은 인스턴스를 가리키는 참조와 인스턴스 자체는 다르다는 점이다.
객체 자신에 대한 참조값을 가진다. (자기 자신을 가리킨다.)
메소드 내에서만 사용된다.
객체 자신을 메소드에 전달하거나 리턴하기 위해 사용된다.
static 메소드에서는 사용할 수 없다.
this.맴버변수
: 매개 변수와 객체 자신이 가지고 있는 변수의 이름이 같은 경우,이를 구분하기 위해 this를 붙인다.
public class Example {
private String ocean;
private String land;
private String people;
public void makingCountry(String ocean, String land, String people) {
// 맴버 변수 = 매개 변수
this.ocean = ocean;
this.land = land;
this.people = people;
}
}
<aside> 💡
Tip. 맴버 변수와 메서드의 매개변수의 이름이 같으면 둘을 어떻게 구분해야 할까?
이 경우, 맴버 변수보다 매개변수가 코드 블럭의 더 안쪽에 있기 때문에 매개변수가 우선순위를 가진다.
맴버 변수에 접근하려면 앞에 this. 이라고 해주면 된다.
여기서 this는 인스턴스 자신의 참조값을 가리킨다.
</aside>
this()
: 해당 클래스의 기본 생성자를 호출한다.
public class Sandwitch {
public String bread;
public String vegetable;
public String meat;
public Stirng source;
// 기본 생성자
public Sandwitch() {
this.bread = "플랫브래드";
this.vegetable = "양상추";
this.meat = "폴드포크 바비큐";
this.source = "랜치";
}
// 빵 종류만 인자로 받는 생성자
public Sandwitch(String bread) {
this();
this.bread = bread;
}
}
this(매개변수)
: 생성자 내에서 다른 생성자를 호출한다.
public class Sandwitch {
public String bread;
public String vegetable;
public String meat;
public Stirng source;
public Sandwitch() {
this("flatBread", "lettuce", "chicken", "mustard")
}
public Sandwitch(String bread, String vegetable, String meat, String source) {
this.bread = bread;
this.vegetable = vegetable;
this.meat = meat;
this.source = source;
}
}