티스토리 뷰


자바에서 this와 super 키워드 사용하기

1. this 키워드

  • this는 현재 클래스의 인스턴스를 가리킵니다.
  • 주로 같은 이름의 매개변수와 클래스 내의 속성을 구분하기 위해 사용됩니다.
  • 생성자에서 매개변수와 클래스 속성의 이름이 같을 때 this를 사용하여 클래스 속성에 값을 할당합니다.

예시:

public class Fruit {
    public String name;
    public String color;
    public double weight;

    public Fruit(String name, String color, double weight) {
        this.name = name;
        this.color = color;
        this.weight = weight;
    }

    public static void main(String[] args) {
        Fruit banana = new Fruit("banana", "yellow", 5.0);
        System.out.println("name: " + banana.name);
        System.out.println("color: " + banana.color);
        System.out.println("weight: " + banana.weight);
    }
}

2. this()와 super()

  • this()는 같은 클래스 내에서 다른 생성자를 호출할 때 사용됩니다. 주로 오버로딩된 생성자에서 초기화 과정을 반복하지 않도록 합니다.
  • super()는 상속받은 부모 클래스의 생성자를 호출할 때 사용됩니다.
  • this()와 super()는 생성자의 첫 줄에서만 사용할 수 있습니다.

예시:

class UpperClass {
    int x;
    int y;

    public UpperClass() {
        x = 10;
        y = 20;
    }

    // 다른 생성자 호출
    public UpperClass(int x) {
        this(); // 자신의 클래스 public UpperClass() 생성자 호출
        this.x = x;
    }
}

class LowerClass extends UpperClass {
    int r;

    public LowerClass() {
        super(); // 상위 클래스의 public UpperClass() 생성자 호출
        r = 30;
    }
}

 

댓글