java oop 29 조상의 생성자 초기화

bitcogo·2022년 7월 26일
0
public class Oop29_ConstructorSuper3 {

    public static void main(String[] args) {
        Point3D7 p3 = new Point3D7(1,2,3);
    }
}
/*
class Point7{
    int x;
    int y;

    Point7(int x,int y){
        this.x = x;
        this.y = y;
    }

    String getLocation(){
        return "x:"+x+", y:"+y;
    }
}

class Point3D7 extends Point7{
    int z;

    Point3D7(int x,int y,int z){
        this.x = x;
        this.y = y;
        this.z = z;
    }

    String getLocation(){ //오버라이딩
        return "x:"+x+", y:"+y+", z:"+z;
    }
}
*/
//위처럼 하면 에러 난다. 그럼 방법 2가지.
/*
class Point7{
    int x;
    int y;

    Point7(){} //1.기본생성자를 만들어준다.

    Point7(int x,int y){
        this.x = x;
        this.y = y;
    }

    String getLocation(){
        return "x:"+x+", y:"+y;
    }
}

class Point3D7 extends Point7{
    int z;

    Point3D7(int x,int y,int z){
        this.x = x;
        this.y = y;
        this.z = z;
    }

    String getLocation(){ //오버라이딩
        return "x:"+x+", y:"+y+", z:"+z;
    }
}
*/
class Point7{
    int x;
    int y;

    Point7(int x,int y){
        this.x = x;
        this.y = y;
    }

    String getLocation(){
        return "x:"+x+", y:"+y;
    }
}

class Point3D7 extends Point7{
    int z;

    Point3D7(int x,int y,int z){
        super(x,y);//2.조상의 생성자 Point7(int x,int y)를 호출
        this.z = z;
    }

    String getLocation(){ //오버라이딩
        return "x:"+x+", y:"+y+", z:"+z;
    }
}
// 2번의 방법이 맞다. 그렇다하더라도 기본생성자는 기본적으로 꼭 추가해주자.
profile
공부하고 기록하는 블로그

0개의 댓글