📝 예제 1 )
class Ex{
public static void main(String args[]){
Child c = new Child();
c.method();
}
}
class Parent {intx = 10; /*super.x*/}
class Child extends Parent{
int x = 20;
void method(){
System.out.println("x="+x);
System.out.println("this.x"+this.x);
System.out.println("super.x"+super.x);
}
}
결과
x=20
this.x=20
super.x=10
📝 예제 2 )
class Ex{
public static void main(String args[]){
Child c = new Child();
c.method();
}
}
class Parent {intx = 10; /*super.x와 this.x 둘 다 가능*/}
class Child extends Parent{
void method(){
System.out.println("x="+x);
System.out.println("this.x"+this.x);
System.out.println("super.x"+super.x);
}
}
결과
x=10
this.x=10
super.x=10
class Point {
int x, y;
Point(int x, int y){
this.x = x;
this.y = y;
}
}
class Point3D extends Point{
int z;
Point3D(int x, int y, int z){
this.x = x; //조상의 멤버를 초기화
this.y = y; //조상의 멤버를 초기화
this.z = z;
}
}
❗ 위와 같이 자손의 생성자에서는 자손이 선언한 것만 초기화를 시켜야하고, 조상의 멤버를 초기화하면 안된다!
아래와 같이 수정해서 작성해야한다😑❗
Point3D(int x, int y, int z){
super(x, y); //조상클래스의 생성자 Point(int x, int y)를 호출
this.z = z; //자신의 멤버를 초기화
}
📌 생성자의 첫 줄에 반드시 생성자를 호출해야한다 !
그렇지 않으면 컴파일러가 생성자의 첫 줄에 super();를 삽입
class Point{
int x;
int y;
point () {
this(0,0);
]
point(int x, int y) {
this.x = x; //생성자의 첫 줄에 생성자를 호출하지 않음
this.y = y;
}
}
✔ 위에 코드처럼 첫 줄에 생성자를 호출하지 않았을 경우 컴파일러가 자동으로 삽입해 준다
class Point{
int x;
int y;
point () {
this(0,0);
]
point(int x, int y) {
super(); //Object();
this.x = x;
this.y = y;
}
}