this
this는 클래스의 현재 인스턴스를 참조하는 키워드이다. 인스턴스 변수와 지역 변수의 이름이 같을 때 이를 구별하는 데 사용됩니다.
double radius;
String color;
public Thiscircle(double radius, String color) {
this.radius = radius;
this.color = color;
}
this. radius 는 멤버필드의 radius를 의미한다.
= radius 는 매개변수의 radius를 의미한다.
가독성을 위해서 의미가 같으면 같은 이름을 사용하기에 발생하는 문제를 this를 사용해서 해결한다.
this()
생성자에서 다른 생성자를 호출할 수 있도록 기존 생성자를 나타내는 this()도 제공한다.
this()를 사용하면 오버로딩된 생성자에서 생기는 중복 코드를 없앨 수 있다.
double radius;
String color;
public Thiscircle(double radius, String color) {
this.radius = radius;
this.color = color;
}
public Thiscircle(double raidus) {
this(radius,"blue");
}
public Thiscircle(String color) {
this(10.0, color);
}
public Thiscircle() {
this(10.0, "red");
}
this()는 첫 번째 메서드를 호출한다.
this()를 사용할 때는 반드시 생성자의 첫 행에 위치해야 한다. 그렇지 않으면 오류가 발생한다.