개발 일지/Java

[Java] this 와 this()

미숫가루설탕많이 2022. 12. 28. 13:55

 this 키워드와 this() 메서드는 매우 유사하게 생겼지만 쓰임새는 전혀 다르다. 간단하게 본다면 this 키워드는 '인스턴스 자신을 가리키는 참조 변수, this() 메서드는 생성자라고 할 수 있다.

 

 

 

 

this


 this 키워드는 생성자의 매개변수로 선언된 변수의 이름이 인스턴스 변수와 같을 때, 인스턴스 변수와 지역변수를 구분하기 위해 사용된다.

 

 모든 메서드에는 자신이 포함된 클래스의 객체를 가리키는 this라는 참조 변수가 있는데 일반적인 경우에는 컴파일러가 'this.'를 추가해주기 때문에 생략하는 경우가 많다. 예를 들어, Example 클래스의 questionName 이라는 인스턴스 필드를 클래스 내부에 출력하고자 한다면 원래는 System.out.println(this.questionName) 이런 방식으로 작성해야 한다.

 

class Example {
    String questionA;	// 인스턴스 변수
    String questionB;
    int score;
    
    Example(String questionA, String questionB, int score) {
        this.questionA = questionA;
        this.questionB = questionB;
        this.score = score;
    }
}

 

 Example() 생성자 안에서 this.questionA는 인스턴스 변수이고, questionA는 매개변수로 정의된 지역변수이다.

 

 결론적으로 this는 인스턴스 자신을 가리키며, 우리가 참조 변수를 통해 인스턴스의 멤버에 접근할 수 있는 것처럼 this를 통해서 인스턴스 자신의 변수에 접근할 수 있다.

 

 

 

 

this()


 this() 메서드는 자신이 속한 클래스에서 다른 생성자를 호출하는 경우에 사용한다. 예를 들어, Example이라는 Example 클래스의 생성자를 호출하는 것은 Example()이 아니라 this()이고 Example() 생성자를 호출하는 것과 동일한 효과를 갖는다.

 

 this() 메서드를 사용하기 위해서는 크게 두 가지 문법요소를 충족시켜야 한다.

 

  1. this() 메서드는 반드시 생성자의 내부에서만 사용할 수 있다.
  2. this() 메서드는 반드시 생성자의 첫 줄에 위치해야 한다.

 

class Example {
    String questionA;
    String questionB;
    int score;

// Example(String questionA, String questionB, int score)를 호출
    Example() {
        this("A번 문제", "B번 문제", 90);
    }

    Example(String questionA, String questionB, int score) {
        this.questionA = questionA;
        this.questionB = questionB;
        this.score = score;
    }
}

 

 위 코드에서 Example() 생성자는 this() 메서드를 통해 Example(String questionA, String questionB, int score) 생성자를 호출하고 있다.

'개발 일지 > Java' 카테고리의 다른 글

[Java] 상속(Inheritance)  (0) 2022.12.29
[Java] 내부 클래스(Inner Class)  (0) 2022.12.28
[Java] 생성자(Constructor, ctor)  (0) 2022.12.28
[Java] 메서드 오버로딩(Method Overloading)  (0) 2022.12.27
[Java] 메서드(Method)  (0) 2022.12.27