super는 자식 클래스에서 부모 클래스로부터 상속받은 멤버를 참조하는데 사용되는 참조변수이다.
다음 예시를 한 번 살펴보자.
class Parent01 {
String str = "사과";
}
class Child extends Parent01 {
String str = "메론";
void print() {
System.out.println("str=" + str );
System.out.println("this.str=" + this.str );
System.out.println("super.str=" + super.str );
}
}
class Test {
public static void main (String args[]) {
Child01 c = new Child01();
c.print();
}
}
위 예시에서 출력된 결과는 다음과 같다.
str = 메론
this.str = 메론
super.str = 사과
결과를 보면 알 수 있듯이 this인지 super인지 따로 적어주지 않으면 자기 자신인 자식 클래스의 멤버를 참조한다.
하지만 부모 클래스와 자식 클래스의 멤버를 구별하기 위해 this와 super를 이용하여 적어주는 것이 좋다.