상속(Inheritance)

moon.kick·2025년 2월 19일
1

Java에서 상속(Inheritance) 을 사용할 때 super 키워드는 부모 클래스의 멤버(필드, 메서드, 생성자)를 호출할 때 사용합니다.

super의 주요 역할

  1. 부모 클래스의 생성자 호출

    • super();를 사용하여 부모 클래스의 생성자를 호출할 수 있음.
    • 부모 클래스에 기본 생성자가 없을 경우, 명시적으로 super(인수...)를 사용해야 함.
  2. 부모 클래스의 메서드 호출

    • 자식 클래스에서 오버라이딩된 부모 클래스의 메서드를 호출할 때 사용.
  3. 부모 클래스의 필드 접근

    • 부모 클래스의 필드를 자식 클래스에서 직접 사용할 때 사용.

1. super를 사용한 부모 클래스 생성자 호출

class Parent {
    int x;

    Parent(int x) {  // 부모 클래스의 생성자
        this.x = x;
        System.out.println("Parent 생성자 호출: x = " + x);
    }
}

class Child extends Parent {
    int y;

    Child(int x, int y) {
        super(x);  // 부모 클래스의 생성자 호출
        this.y = y;
        System.out.println("Child 생성자 호출: y = " + y);
    }
}

public class SuperExample {
    public static void main(String[] args) {
        Child child = new Child(10, 20);
    }
}

🔹 실행 결과

Parent 생성자 호출: x = 10
Child 생성자 호출: y = 20

super(x);를 사용하여 부모 클래스의 생성자를 먼저 호출한 후, 자식 클래스의 생성자가 실행됨.


2. super를 사용한 부모 클래스의 메서드 호출

class Parent {
    void display() {
        System.out.println("부모 클래스의 display() 메서드 호출");
    }
}

class Child extends Parent {
    void display() {
        super.display(); // 부모 클래스의 display() 호출
        System.out.println("자식 클래스의 display() 메서드 호출");
    }
}

public class SuperMethodExample {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.display();
    }
}

🔹 실행 결과

부모 클래스의 display() 메서드 호출
자식 클래스의 display() 메서드 호출

super.display();를 사용하여 부모 클래스의 display() 메서드를 호출한 후, 자식 클래스의 display()가 실행됨.


3. super를 사용한 부모 클래스의 필드 접근

class Parent {
    int num = 100;
}

class Child extends Parent {
    int num = 200;

    void show() {
        System.out.println("자식 클래스 num: " + num);
        System.out.println("부모 클래스 num: " + super.num);
    }
}

public class SuperFieldExample {
    public static void main(String[] args) {
        Child obj = new Child();
        obj.show();
    }
}

🔹 실행 결과

자식 클래스 num: 200
부모 클래스 num: 100

super.num을 사용하여 부모 클래스의 num 필드에 접근 가능.


📌 결론: super는 부모 클래스를 참조하는 키워드

  • super(); → 부모 클래스의 생성자를 호출
  • super.메서드(); → 부모 클래스의 메서드를 호출
  • super.필드명 → 부모 클래스의 필드에 접근

🔹 부모 클래스의 멤버(필드, 메서드)를 명확히 구분해서 사용해야 할 때 super를 활용하면 된다! 🚀

profile
@mgkick

0개의 댓글