Java/Java Concept

this와 this()

SeungbeomKim 2022. 7. 4. 21:13
반응형

this 참조 변수

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;

    }

    ...

}

위의 코드와 같이 생성자의 매개변수 이름과 인스턴스 변수의 이름이 같은 경우 인스턴스 변수 앞에 this 키워드를 붙여 이를 구분해야 한다. this 참조변수는 인스턴스 메소드에만 사용할 수 있으며 클래스 메소드 내에서는 사용할 수 없다.

this() 메소드

this() 메소드는 생성자 내부에서만 사용할 수 있으며, 같은 클래스의 다른 생성자를 호출할 때 사용한다.

this() 메소드에 인수를 전달하면, 생성자 중에서 메소드 시그니처가 일치하는 다른 생성자를 찾아 호출해준다.

메소드 시그니처(method signature) : 메소드의 이름과 메소드의 원형에 명시되는 매개변수 리스트

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("소나타", 2012, "검정색", 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());

    }

}

우의 코드와 같이 첫번째 생성자는 this 참조 변수를 사용하여 인스턴스 변수에 접근하지만,

두번째 생성자는 this() 메소드를 이용해 첫번째 생성자를 호출한다.

내부적으로 다른 생성자를 호출하여 인스턴스 변수를 초기화할 수 있다.

반응형

'Java > Java Concept' 카테고리의 다른 글

패키지(package) 개념  (1) 2022.07.08
메소드 오버로딩  (1) 2022.07.04
생성자 개념  (1) 2022.07.04
메소드 개념  (0) 2022.07.04
클래스 선언  (1) 2022.07.04