Java에서 this는 어떤 의미일까?

상곤·2025년 4월 16일

Java

목록 보기
15/22
post-thumbnail

Java에서 this는 자주 보이지만 제대로 이해하지 못하는 경우가 많았다.. (까먹어서..)

이 글에서는 this가 어떤 의미인지, 어떻게 쓰이는지 예제로 정리해보겠다!

this란?

this는 현재 객체를 가리킨다.

용도예시설명
인스턴스 변수 참조this.x = x;매개변수와 인스턴스 변수 이름이 같을 때 구분
같은 클래스의 다른 생성자 호출this(값);오버로딩된 생성자 호출
람다 표현식 내부에서 외부 객체 참조ClassName.this외부 클래스 참조 시 사용

인스턴스 변수 참조

Class

class MyClass {
    int a;

    MyClass(int a) {
        a = a;  // 둘 다 매개변수 a를 가리킴
    }

    void print() {
        System.out.println(a);
    }
}

Main

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass(10);
        obj.print();
    }
}

이런 코드가 있을 때, 출력 결과는 어떻게 될까?

0

0이 나온다.

this를 사용하지 않으면,
a는 둘다 매개변수 a를 가리키기 때문이다.

그래서 아래와 같이 this.a라고 해서 자기 자신 객체의 인스턴스 변수를 가리켜서 저장해야 한다.

    MyClass(int a) {
          // 인스턴스 변수 a
          // ↓
        this.a = a;  // 인스턴스 변수 a에 매개변수 a를 대입
        	  // ↑ 
			  // 매개변수 a
    }

그렇게 하면 아래와 같이 매개변수 a로 초기화된 값 10이 제대로 나온다!

super와의 관계

  • super는 부모 클래스의 생성자나 멤버를 참조할 때 사용된다.
  • this()super()는 동시에 사용할 수 없다. 생성자 내에서 가장 첫 줄에만 한 번 사용할 수 있다.

Class

class Parent {
    int x;

    Parent() {
        this(1);  // 같은 클래스 내 다른 생성자 호출
        System.out.println("2. Parent Class의 기본 생성자 호출");
    }

    Parent(int x) {
        this.x = x;
        System.out.println("1. this()를 통한 Parent Class 생성자 호출, x = " + x);
    }
}

class Child extends Parent {
    int x;

    Child() {
        this(3);  // 자식 클래스의 다른 생성자 호출
        System.out.println("4. Child() 생성자 호출");
    }

    Child(int x) {
        super();     // 부모 클래스 기본 생성자 호출
        this.x = x;
        System.out.println("3. this()를 통한 Child Class 생성자 호출, x = " + x);
    }

    int getX() {
        return this.x;
    }

    int getParentX() {
        return super.x;
    }
}

main

class Main {
    public static void main(String[] args) {
        Child c = new Child();
        System.out.println("Child x: " + c.getX());
        System.out.println("Parent x: " + c.getParentX());
    }
}

이때 출력은 어떻게 될까?

한 번 코드 흐름을 따라가면서 출력을 예상해보자!

출력 결과

1. this()를 통한 Parent Class 생성자 호출, x = 1
2. Parent Class의 기본 생성자 호출
3. this()를 통한 Child Class 생성자 호출, x = 3
4. Child() 생성자 호출
Child x: 3
Parent x: 1

코드 흐름을 한 번 따라가보자

실행 순서

Child() -> this(3)
Child(int x(3)) -> super()
Parent() -> this(1)
Parent(int x(1))

1. Child c = new Child();

Child() 호출
-> 내부에서 this(3) 호출
-> Child(int x) 생성자 실행

2. Child(int x) 내부

super() 호출
-> Parent() 생성자 실행

3. Parent() 내부

this(1) 호출
-> Parent(int x) 생성자 실행
-> this.x = x; Parent의 인스턴스 변수 x에 매개변수로 넘겨 받은 1 저장
-> System.out.println("1. this()를 통한 Parent Class 생성자 호출, x = " + x); 출력

4. Parent() 생성자 내부

System.out.println("2. Parent Class의 기본 생성자 호출"); 출력

5. Child(int x) 생성자 내부

this.x = x; Child의 인스턴스 변수 x에 매개변수로 넘겨 받은 3 저장
-> System.out.println("3. this()를 통한 Child Class 생성자 호출, x = " + x); 출력

6. Child() 생성자 내부

System.out.println("4. Child() 생성자 호출"); 출력

그리고 3, 5 단계에서 인스턴스 변수에 저장한 x의 값들을 각각 메서드를 통해서 출력한다

🙄부모 생성자가 두 번 호출되지는 않는가?

자식 생성자 내부에서 super()로 직접 호출했기 때문에 부모 생성자가 자동으로 또 호출되지 않는다.

이 글에서 부모 클래스 생성자의 자동 호출에 대해서 다뤄놓았다.

profile
🫠

0개의 댓글