this

인철·2023년 10월 13일

Java

목록 보기
28/52

this

this

  • java에서 사용하는 특수한 키워드
  • 현재 객체를 가리킴

사용 상황

  • 인스턴스 변수 접근 : 현재 객체의 인스턴스 변수에 접근할 때 사용
  • 인스턴스 메서드 호출 : 동일한 클래스 내의 다른 메서드를 호출할 때 사용
  • 생성자 호출 : 동일한 클래스 내에서 다른 생성자를 호출할 때
public class MyClass {
    private int number;

    // 생성자
    public MyClass(int number) {
        this.number = number; // 'this'를 사용하여 인스턴스 변수에 접근
    }

    // 메서드
    public void doSomething() {
        System.out.println("Doing something");
        this.anotherMethod(); // 'this'를 사용하여 다른 메서드 호출
    }

    // 다른 메서드
    public void anotherMethod() {
        System.out.println("Another method");
    }

    // 생성자 체이닝을 사용하는 예제
    public MyClass() {
        this(42); // 'this'를 사용하여 다른 생성자 호출
    }
}
profile
같은글이있어도양해부탁드려요(킁킁)

0개의 댓글