super 키워드

super는 부모 클래스로부터 상속받은 필드나 메소드를 자식 클래스에서 참조하기 위해 쓰는 참조 변수

인스턴스 변수의 이름과 지역 변수의 이름이 같을 경우 인스턴스 변수 앞에 this 키워드를 사용하여 구분할 수 있다. 마찬가지로 부모 클래스의 멤버와 자식 클래스의 멤버 이름이 같을 경우 super 키워드를 사용하여 구분할 수 있다

super 변수를 사용하여 부모 클래스의 멤버에 접근할 수 있다 this와 마찬가지로 super 변수를 사용할 수 있는 것은 인스턴스 메소드 뿐이며 클래스 메소드에서는 사용할 수 없다

class Parent { 
		int a = 10; 
}

class Child extends Parent {
    void display() {
        System.out.println(a);
        System.out.println(this.a);
        System.out.println(super.a);
    }
} 

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

>> 실행 결과
10
10
10
class Parent {
    int a = 10;
} 

class Child extends Parent {
    int a = 20;
    void display() {
        System.out.println(a);
        System.out.println(this.a);
        System.out.println(super.a);
    }
} 

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

>> 실행 결과
20
20
10

int형 변수가 부모 클래스에만 선언되어으므로 this, super 모두 같은 값을 출력

int형 변수가 부모 클래스와 자식 클래스 모두 선언되어 있기 때문에 this는 자식 클래스, super는 부모 클래스의 값을 출력합니다

super() 메소드

this() 메소드가 같은 클래스의 다른 생성자를 호출할 때 사용된다면 super() 메소드는 부모 클래스의 생성자를 호출할 때 사용된다

자식 클래스의 인스턴스를 생성하면 해당 인스턴스에는 자식 클래스의 고유 멤버와 부모 클래스의 모든 멤버를 포함한다. 따라서 부모 클래스의 멤버를 초기화하기 위해서 자식 클래스의 생성자에 부모 클래스의 생성자까지 호출해야 하기 때문에 모든 클래스의 부모 클래스인 Object 클래스의 생성자까지 거슬러 올라가며 수행

부모 클래스의 생성자를 명시적으로 호출하지 않는 모든 자식 클래스의 생성자 첫 줄에 자동으로 다음과 같은 명령문을 추가하여, 부모 클래스의 멤버를 초기화할 수 있도록 해준다

super();

class Parent {
    int a;
    Parent() { a = 10; }
    Parent(int n) { a = n; }
}

class Child extends Parent {
    int b;
    Child() {
①      //super(40);
        b = 20;
    }
    void display() {
        System.out.println(a);
        System.out.println(b);
    }
} 

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

>> 실행 결과
10
20
class Parent {
    int a;
    Parent() { a = 10; }
    Parent(int n) { a = n; }
}

class Child extends Parent {
    int b;
    Child() {
①      super(40);
        b = 20;
    }
    void display() {
        System.out.println(a);
        System.out.println(b);
    }
} 

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

>> 실행 결과
40
20