[Java] super(슈퍼)
super 지시어
참조변수 super
super는 슈퍼클래스에서 상속받은 내용을 참조할 때 사용하는 변수가 super이다.
멤버변수와, 지역변수의 이름이 같을 때 this를 붙여서 사용하듯이 상속받은 멤버와 자신의 멤버와 이름이 같을 때 super를 붙여서 사용할 수 있다.
public class A {
int age = 33;
}
public class B extends A {
int age = 22;
public static void main(String[] args){
B b = new B();
System.out.purintln(b.age);
}
}
이런 경우 b.age라고 출력을 한 경우 22가 출력된다.
만약 33을 출력하고 싶다면 System.out.purintln(super.b.age); super을 사용하면 슈퍼(부모)클래스인 33을 출력이 가능하게 된다.
public class B extends A {
int age = 22;
public static void main(String[] args){
B b = new B();
System.out.purintln(super.b.age);
}
}
super() - 조상의 생성자
super()은 this()와 같은 개념이라고 생각하면 된다.
예시로,
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class PointServe extends Point {
int z;
PointServe(int x, int y) {
super (x, y); // 조상클래스의 생성자 Pint(int x, int y)를 호출
this.z = z; // 자신의 멤버변수를 초기화
}
}
댓글남기기