본문 바로가기

Web/JAVA

[Java] this

728x90

https://www.baeldung.com/java-this

 

 

this 는 method가 호출되는 현재 객체에 대한 참조이다

 

이 this는 자주 쓰면서도 정확한 개념을 모르는 경우가 많다

 

 

 

Disambiguating Field Shadowing

instance 변수와 로컬 매개변수를 구분할때 유용하다

인스턴스 필드와 이름이 같은 생성자 매개변수가 있을 때 매개변수와 구분하기 위해 this를 사용한다

public class KeywordTest {

    private String name;
    private int age;
    
    public KeywordTest(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

 

 

Referencing Constructors of the Same Class

constructor에서 this() 를 이용하여 동일한 클래스의 다른 constructor를 호출할 수 있다

코드사용량을 줄이기에 용이하다

public KeywordTest(String name, int age) {
    this();
    
    // the rest of the code
}

또는 인수가 없는 생성자에 매개변수 생성자를 호출하고 인수를 전달할 수 있다

이때 this() 가 첫번째 명령문이여야 컴파잉오류가 나지 않는다

public KeywordTest() {
    this("John", 27);
}

 

 

 

Passing this as a Parameter

printInstance() method 에서 this 키워드 인수가 정의된다

public KeywordTest() {
    printInstance(this);
}

public void printInstance(KeywordTest thisKeyword) {
    System.out.println(thisKeyword);
}

이렇게 하면 constructor 내에서 printInstance() method를 호출하고 현재 instance에 대한 참조를 전달한다

 

 

 

 

Returning this

현재의 인스턴스를 반환시킨다

https://www.baeldung.com/creational-design-patterns

 

 

 

The this Keyword Within the Inner Class

inner class 내에서 외부 클래스 instance에 액세스 할 수 있다

public class KeywordTest {

    private String name;

    class ThisInnerClass {

        boolean isInnerClass = true;

        public ThisInnerClass() {
            KeywordTest thisKeyword = KeywordTest.this;
            String outerString = KeywordTest.this.name;
        }
    }
}

KeywordTest 의 인스턴스에 대한 참조를 innerClass에서 얻을 수 있다

 

728x90

'Web > JAVA' 카테고리의 다른 글

[Java] Super  (0) 2023.03.23
[Java] Interface Supplier<T>  (0) 2023.03.22
[IntelliJ Javadocs] Javadocs 문서 만들기  (0) 2023.03.18
[Java] try-with-resources  (0) 2023.02.25
[JAVA 8↑] Stream  (0) 2023.02.21