super.
- 객체 자신을 가리키는 참조변수.
- 인스턴스 메소드(생성자) 내에만 존재
- ✨조상의 멤버✨ - 자신의 멤버로부터 구별할 때
class Parent {
int x = 10; // <- super.x
}
class Child extends Parent {
int x = 20; // <- this.x
// 주의!! 이름이 같다고 초기화가 되는 게 아니라 다른 변수임!!!
// 멤버가 !!!****3개****!!
void method() {
System.out.println("x = "+x); // 가장 가까운 애
System.out.println("this.x = "+this.x); // iv
System.out.println("super.x = "+super.x); // 조상의 멤버
}
}
public class Ex7_02 {
public static void main(String[] args) {
//
Child c = new Child();
c.method();
}
}
x = 20
this.x = 20
super.x = 10
class Parent2 {
int x = 10;
}
class Child2 extends Parent2 {
// 이번엔 자식에 따로 변수 없음
// 멤버 2개***!!!
void method() {
System.out.println("x = "+x);
System.out.println("this.x = "+this.x);
System.out.println("super.x = "+super.x);
}
}
public class Ex7_03 {
public static void main(String[] args) {
//
Child2 c = new Child2();
c.method();
}
}
x = 10
this.x = 10
super.x = 10
-> 좀 변형해서! 요거 기억하자
class Parent2 {
int x = 10;
}
class Child2 extends Parent2 {
// 이번엔 자식에 따로 변수 없음
// 멤버 2개***!!!
// int x = 20; --> 하면 this.x = 20 나옴
void method() {
int x = 15;
System.out.println("x = "+x); // 제일 가까운 애 = 15
System.out.println("this.x = "+this.x); // iv
System.out.println("super.x = "+super.x); // 조상 = 10
}
}
public class Ex7_03 {
public static void main(String[] args) {
//
Child2 c = new Child2();
c.method();
}
}
x = 15
this.x = 10
super.x = 10
super()
- 조상의 생성자를 호출할 때
- ✨조상의 멤버는 조상의 생성자를 호출해서 초기화
- 조상의 멤버를 자식이 직접 초기화할 수 없기 때문에!!
- ✨✨✨모든 생성자의 첫 줄에 반드시 생성자를 호출해야 한다.
- 모든 생성자는
Object()
를 상속받기에 저절로super();
가 자동 추가돼서 우리가 따로 넣지 않았던 것this()
로 자기자신을 호출해도 된다.- ✨✨✨모든 클래스는 생성자를 반드시 갖고 있다.
class Point {
int x, y;
Point(int x, int y) {
super(); // 조상인 Object()생성자 호출. 컴파일러가 자동으로
this.x = x; // 매개변수를 받아 iv 초기화
this.y = y;
}
}
class Point3D extends Point{
int z;
Point3D(int x, int y, int z) {
super(); // 조상인 Point()생성자 호출. 컴파일러가 자동으로
//-> ***에러 : 기본생성자인 Point()가 없기 때문에!!!
this.x = x;
this.y = y;
this.z = z;
}
}
모든 생성자의 첫 줄엔 생성자를 호출해야 하는데, 없으면 자동으로 super()
를 추가하여 조상의 기본생성자를 자동 호출한다.
📢📢에러 : 기본생성자인 Point()
가 없기 때문에!!!
-> 해결 1) 기본생성자 ✨Point()
를 추가거나
-> 해결 2) 아래와 같이 다른 생성자인 Point(x, y)
를 호출하는 ✨✨super(x, y);
를 추가하면 된다.
class Point {
int x, y;
Point(int x, int y) {
super(); // 조상인 Object()생성자 호출. 컴파일러가 자동으로
this.x = x; // 매개변수를 받아 iv 초기화
this.y = y;
}
}
class Point3D extends Point{
int z;
Point3D(int x, int y, int z) {
super(x, y); //<-- 요런식으로 조상인 Point(x, y)생성자 호출해서 매개변수 받아 iv 초기화
this.z = z;
}
}