Rule
1. 생성자의 이름으로 클래스 이름 대신 this를 사용한다.
2. 한 생성자에서 다른 생성자를 호출할때는 반드시 첫 줄에서만 호출이 가능하다.
class Car {
String color; // 색상
String gearType; // 변속기 종류 - auto(자동), manual(수동)
int door; // 문의 개수
Car() {
this("white", "auto", 4);
}
Car(String color) {
this(color, "auto", 4);
}
Car(int door){
this("white", "auto", door);
}
Car(String color, String gearType, int door) {
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
코드와같이 기본값을 설정해줄때 유용하다.
Car(String c, String g, int d){
color = c;
geerType = g;
door = d;
}
Car(String color, String geerType, int door){
this.color = color;
this.geerType = geerType;
this.door = door;
}
아래와같이 코드를 작성하면 수정이 필요할때 적은 코드만 변경하면 되므로 유지보수가 쉬워진다.