this vs this()

박영준·2023년 7월 3일
0

Java

목록 보기
102/111

1. this 정의

  • 인스턴스 자기 자신(객체의 주소)을 가리키는 키워드

  • this 를 통해, 클래스 메소드/생성자에서 자기 자신의 데이터를 조작할 수 있다.

    주의!
    static 메소드에서는 사용할 수 없다.

2. this vs this()

this

this.멤버변수

  • 자신의 객체에 접근할 때 사용

  • 매개 변수와 객체 자신이 가지고 있는 변수의 이름이 같은 경우, 이를 구분하기 위해 this 를 붙인다

this()

this(매개변수)

  • 같은 클래스에서 생성자가 다른 생성자를 호출할 때 사용

  • 주로 코드의 중복을 줄일 목적으로 사용

3. 예시

예시 1

1. Book 클래스 정의


① this는 객체 자신에 대한 레퍼런스 변수로, this.price 는 멤버변수 price를 나타냅니다.
② this( )는 생성자안에서 다른 생성자를 호출하므로, this(title, 0); 는 매개변수 2개를 가진 생성자를 호출하게 됩니다.

2. Book 객체 생성/실행

3. 실행결과

예시 2

public class Car {
    private String modelName;
    private int modelYear;
    private String color;
    private int maxSpeed;
    private int currentSpeed;

    public Car(String modelName, int modelYear, String color, int maxSpeed, int currentSpeed) {
        this.modelName = modelName;
        this.modelYear = modelYear;
        this.color = color;
        this.maxSpeed = maxSpeed;
        this.currentSpeed = 0;
    }
}
  • '생성자의 매개변수 명 = 객체 명' 이므로, 객체에 this 를 붙여 구분했다.
profile
개발자로 거듭나기!

0개의 댓글