Back-End/Java

[자바 / Java] super 키워드와 super()

Kangharyeom 2022. 9. 6. 16:04
728x90

this와 this()의 차이와 비슷하다.

 

이들은 모두 상위 클래스의 상속관계를 전제한다.

super 키워드는 상위 클래스의 객체, super()는 상위 클래스의 생성자를 호출하는 것을 의미한다.

 

super 키워드

 

public class Super {
    public static void main(String[] args) {
        childClass exam = new childClass();
        exam.score();
    }
}

class Parents {
    int count = 50; // super.count
}

class childClass extends Parents {
    int count = 30; // this.count

    void score() {
        System.out.println("count = " + count);
        System.out.println("this.count = " + this.count);
        System.out.println("super.count = " + super.count);
    }
}

// 출력값
count = 30
count = 30
count = 50

 

this.는 객체 안에서 변수를 출력하여준다.

하지만, super는 상위클래스의 변수를 출력하여준다. 즉, 상위클래스의 생성자를 호출해준다.

 

super()

 

super()는 생성자를 호출 할 때 사용한다. 하지만, this()는 같은 클래스의 다른 생성자를 호출 할 때 사용되는 반면, super()은 상위클래스의 생성자를 호출하는데 사용된다.  

 

public class Super {
    public static void main(String[] args) {
        Child exam = new Child();
    }
}

class Parents {
    Parents() {
        System.out.println("상위 클래스 생성자");
    }
}

class Child extends Parents { // Parents 클래스로부터 상속
    Child() {    
        super(); // 상위 클래스의 생성자 호출
        System.out.println("하위 클래스 생성자");
    }
}

// 출력값
상위 클래스 생성자
하위 클래스 생성자

다음과 같이 super()는 상위 클래스의 생성자를 호출해준다. 

다만 반드시 생성자 안에서만 사용 가능하고, 반드시 첫 줄에 와야한다.