super키워드는 부모클라스의 메소드나 필드를 상속 받을 때 쓰는 참조변수이다.
인스턴스 변수와 지역변수의 이름이 같을 경우 this 키워드를 통해 가져왔는데,
super도 이와 같은 맥락으로 부모클라스와 자식 클라스의 맴버가 같을 경우 super를 써서 데려올 수 있다.
코드를 통해 자세히 살펴보자..
1.변수가 부모클라스에서만 선언되는 경우 모든 변수가 같은 값을 출력한다.
public class PracticeSuper {
public static void main(String[] args){
Child ch = new Child();
ch.display();
}
}
class Parent{
int a = 10;
}
class Child extends Parent{
public void display(){
System.out.println(a);
System.out.println(this.a);
System.out.println(super.a);
}
}
int a = 10 은 부모 클라스에서만 선언되어있다. 따라서 지역 변수와 this 참조 변수 그리고 super 참조 변수 모두 같은 값을 출력한다.
2.상속클라스에서도 변수를 입력하면, super 참조 변수만이 부모클래스에서 대입된 값을 출력해준다.
public class PracticeSuper {
public static void main(String[] args){
Child ch = new Child();
ch.display();
}
}
class Parent{
int a = 10;
}
class Child extends Parent{
int a = 20;
public void display(){
System.out.println(a);
System.out.println(this.a);
System.out.println(super.a);
}
}
답은 20,20,10 이 나온다 !
'Java' 카테고리의 다른 글
Try-catch 예외처리 (0) | 2022.01.07 |
---|---|
Super() 메소드 (0) | 2022.01.07 |
this참조 변수와 this()메소드 (0) | 2022.01.07 |
i++랑 ++i의 차이점 (0) | 2022.01.07 |
== 와 .equals의 차이점 (0) | 2022.01.07 |
댓글