생성자 this()는 같은 클래스 안에 있는 다른 생성자
를 호출할 때 사용한다.
예를 들어, A라는 클래스가 있을 때 this(3)이라면 A(3), 즉 int 데이터 하나를 입력받는 생성자를 호출하라는 의미이다.
생성자 this()를 사용하면 생성자의 초기화 시 중복을 제거할 수 있다는 장점이 있다.
위와 같은 규칙 둘 중 어느 하나라도 지키지 않으면 this() 생성자 사용 시 오류가 발생한다.
class Account {
int id;
String name;
int balance;
Account(int id, String name, int money) {
this.id = id;
this.name = name;
this.balance = money;
}
Account(int id) {
this.balance = 0;
this(id, "홍길동"); // 오류 - 생성자의 첫 줄에 위치해야 함
}
Account(int id) {
this(id, "홍길동"); // 생성자의 첫 줄에 위치
this.balance = 0;
}
Account(int id, String name) {
this(id, name, 0);
}
}