1. super 란 무엇인가
: 자손 클래스에서 조상 클래스로부터 상속받은 맴버를 참조하는 변수이다. 멤버변수와, 지역변수 이름의 같을 때 this를 사용해서 구별했듯이 상속받은 맴버와 자신의 맴버와 이름이 같을 때 super를 써서 구별할 수 있다.
class Parents {
int x = 10;
}
class Child extends Parents{
int x = 20;
public void print() {
System.out.println("x : " + x);
System.out.println("this.x : " + this.x);
System.out.println("super.x : " + super.x);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.print();
}
}
2. super() 호출 순서
class God {
int x = 100;
God(int x) {// 6
this.x = x;// 7
}
}
class Parents extends God {
int y = 10;
Parents(int x, int y) {// 4
super(x);// 5
this.y = y;// 8
}
}
class Child extends Parents {
int z = 20;
Child(int x, int y, int z) {// 2
super(x, y);// 3
this.z = z;// 9
}
public void print() {// 11
System.out.println("x : " + x);
System.out.println("y : " + y);
System.out.println("z : " + z);
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child(100, 200, 300);// 1
child.print();// 10
}
}
'Java' 카테고리의 다른 글
[Java] 5. Object 클래스 (0) | 2022.03.16 |
---|---|
[Java] 4. static 메소드와 인스턴스 메소드 (0) | 2022.03.15 |
[Java] 3. 향상된 for문 (0) | 2022.03.15 |
[Java] 2. 변수 (0) | 2022.03.15 |
[Java] 1. Java를 시작하기 전에 (0) | 2020.11.30 |