개발/Java
[Java] this와 this()
서해쭈꾸미
2024. 4. 24. 00:00
this
this는 instance 자신을 가르킨다. 진짜 this임.
convention처럼 생각하는게 좋음. 객체의 필드를 사용할 떈 무조건 this를 붙여주자.
this가 필요한 이유
아래처럼 생성자를 선언하는데 매개변수명과 객체의 필드명이 동일할 경우
오류가 발생하지는 않지만 생성자 블록 내부에서 해당 변수들은 객체의 필드가 아닌 가장 가까운 매개변수명을 가리키게 됨으로 자기 자신에게 값을 대입하는 상황이 되어 버린다.
public Car(String model, String color, double price) {
model = model;
color = color;
price = price;
}
이때 this를 사용하면 된다.
public Car(String model, String color, double price) {
this.model = model;
this.color = color;
this.price = price;
}
추가로, 객체의 메서드에서 리턴타입이 인스턴스 자신일 떄, this를 사용해 인스턴스 자신의 주소를 리턴 수 있다.
Car returnInstance() {
return this;
}
this()
this()는 인스턴스 자신의 생성자를 호출하는 키워드이다.
필드 코드의 중복을 줄일 때 사용된다.
public Car(String model) {
this.model = model;
this.color = "Blue";
this.price = 50000000;
}
public Car(String model, String color) {
this.model = model;
this.color = color;
this.price = 50000000;
}
public Car(String model, String color, double price) {
this.model = model;
this.color = color;
this.price = price;
}
얘를
public Car(String model) {
this(model, "Blue", 50000000);//마지막 생성자를 호출한 것
}
public Car(String model, String color) {
this(model, color, 100000000); //마지막 생성자를 호출한
}
public Car(String model, String color, double price) {
this.model = model;
this.color = color;
this.price = price;
}
this()를 사용해 이런식으로 줄일 수 있다.
주의할점 !!
this() 키워드를 사용해서 다른 생성자를 호출할 때는 반드시 해당 생성자의 첫 줄에 작성되어야 한다.
//이런거 안 됨 !!
public Car(String model) {
System.out.println("model = " + model); //에러
this(model, "Blue", 50000000);
}