JAVA
This
천재도담
2020. 8. 31. 22:43
통상적으로 필드와 동일한 이름을 갖는 매개변수를 사용
->이 경우 필드와 매개 변수 이름이 동일하기 때문에 생성자 내부에서 해당 필드에 접근 할 수 없음
->동일한 이름의 매개변수가 사용 우선순위가 높기 때문에
1. 객체 자신을 가르키는 것 ! (앞으로 생성될 객체의 주소를 담을 곳이라고 가정)
2. this 객체 자신( 생성자 호출) >> 원칙 : 여러개의 생성자 호출
class Socar {
String color;
String geartype;
int door;
Socar(){ //기본설정
this.color = "red";
this.geartype = "auto";
this.door =2;
}
Socar(String color, String geartype, int door) {
this.color = color;
this.geartype = geartype;
this.door = door;
}
void print(){
System.out.println(this.color + "/" + this.geartype + "/" + this.door);
}
}
This() 다른생성자 호출
생성자 오버로딩이 많아질 경우 생성자 간의 중복된 코드 발생할 경우가 많음 -> 필드 초기화 내용은 한 생성자에만 집중적으로 작성하고 나머지 생성자는 초기화 내용을 가지고 있는 생성자를 호출하는 방법으로 개선 가능 (중복코드를 줄이기 위함)
생성자의 첫 줄에서만 허용
호출되는 생성자의 매개변수에 맞게 제공해야함
Zcar(){ //기본설정
// this.color = "red";
// this.geartype = "auto";
// this.door =2;
this("red","auto",2); // 나를 다시 호출하네
System.out.println("default constructor");
}