min's devlog
this와 this() 본문
this
- 객체 자신을 가리키는 레퍼런스
- 현재 실행되고 있는 메소드가 속한 객체에 대한 레퍼런스
this의 사용
- 매개변수의 이름을 멤버 변수와 같은 이름으로 붙이고자 할 때 사용
public int getRadius(){
return radius;
}
- 메소드가 객체 자신의 레퍼런스를 리턴해야하는 경우에 this 리턴
public Circle getMe() {
return this;
}
this()
- 생성자 내부에서만 사용할 수 있으며, 같은 클래스의 다른 생성자를 호출할 때 사용
- 인수를 전달하면, 생성자 중에서 메소드 시그니처가 일치하는 다른 생성자를 찾아 호출해준다.
class Car {
private String modelName;
private int modelYear;
private String color;
private int maxSpeed;
private int currentSpeed;
Car(String modelName, int modelYear, String color, int maxSpeed) {
this.modelName = modelName;
this.modelYear = modelYear;
this.color = color;
this.maxSpeed = maxSpeed;
this.currentSpeed = 0;
}
Car() {
this("소나타", 2022, "검정색", 160); // 다른 생성자를 호출
}
public String getModel() {
return this.modelYear + "년식 " + this.modelName + " " + this.color;
}
}
public class Method05 {
public static void main(String[] args) {
Car tcpCar = new Car(); System.out.println(tcpCar.getModel());
}
}
'til > Java' 카테고리의 다른 글
재귀 호출(recursive call) (0) | 2022.03.21 |
---|---|
메소드 오버로딩 (0) | 2022.03.21 |
생성자(Constructor) (0) | 2022.03.21 |
객체와 인스턴스 (0) | 2022.03.20 |
객체 지향과 클래스 (Class) (0) | 2022.03.20 |
Comments