티스토리 뷰

Java+Spring/Java

[Java]super vs. super()

Vagabund.Gni 2022. 7. 13. 22:56
728x90
반응형

예전 글에서 this() 메서드와 this 키워드에 관해서 살펴봤다.

 

https://gnidinger-coding.tistory.com/11

 

[Java]this() vs. this

this() this() 메서드는 클래스 안에서 생성자를 상호 호출할 때 사용한다. 조금 더 풀어서 쓰자면, 생성자 안에서 다른 생성자를 호출할 때 사용되는 것이 this() 메서드이다. this() 메서드를 사용하

gnidinger-coding.tistory.com

 

요약하면 this는 자신의 객체, this()는 자신의 생성자를 호출하는 데 사용되었다.

 

super와 super()도 이와 비슷하게 사용된다. 다만 차이점은

 

super는 상위 클래스의 객체, super()는 상위 클래스의 생성자를 호출하는 데 사용된다는 점이다.

 

당연하게도 상위 클래스의 존재가 상정되어 있으며, 상속 관계를 전제로 한다.

 

그럼 먼저 super에 관해 알아보자.

public class Super {
    public static void main(String[] args) {
        Lower l = new Lower();
        l.callNum();
    }
}

class Upper {
    int count = 20; // super.count
}

class Lower extends Upper {
    int count = 15; // this.count

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

// 출력 결과
count = 15
count = 15
count = 20

위 예에서 Lower 클래스는 Upper 클래스로부터 변수 count를 상속받는데,

 

상위 클래스의 변수와 하위 클래스의 변수의 이름이 같은 것을 볼 수 있다.

 

이 경우 둘을 구분하기 위한 키워드가 super이며, 세 번째의 super.count의 출력 결과가

 

상위 클래스의 count 변수임을 확인할 수 있다.

 

참고로, 키워드가 없는 count는 가장 가까운 count 변수를 가리키기 때문에 15가 출력되며,

 

this.count는 자신의 객체의 count를 가리키기 때문에 역시 15가 출력된다.

 

계속해서 super() 메서드에 대해 알아보자.

public class Test {
    public static void main(String[] args) {
        Student s = new Student();
    }
}

class Human {
    Human() {
        System.out.println("휴먼 클래스 생성자");
    }
}

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

// 출력 결과
휴먼 클래스 생성자
학생 클래스 생성자

위 예에서는 Student 클래스가 Human 클래스를 상속받고 있으며,

 

super() 메서드를 통해 상위 클래스인 Human의 Human() 생성자를 호출하고 있음을 볼 수 있다.

 

따라서 "휴먼 클래스 생성자"가 먼저 출력이 된다.

 

super() 메서드는 this() 메서드와 비슷하게 반드시 생성자의 첫 줄에 선언되어야 하며,

 

super()가 없는 경우 컴파일러는 자동으로 super()를 삽입한다.

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함