Java继承构造方法的注意点

父类:注意(x,y是private,不能继承到子类中)

class Par{
   private int x;
   private int y;
   int a;
   public Par(){

   }

   public Par(int x, int y) {
       this.x = x;
       this.y = y;
       System.out.println("Par...");
   }

   public int getX() {
       return x;
   }

   public void setX(int x) {
       this.x = x;
   }

   public int getY() {
       return y;
   }

   public void setY(int y) {
       this.y = y;
   }

   public int getA() {
       return a;
   }

   public void setA(int a) {
       this.a = a;
   }
}

子类

class Son extends Par{

    public Son(int x,int y) {
        super(x,y);
        System.out.println("Son...");
        a=x+y;
    }
} 

主函数

public class Test01 {

    public static void main(String[] args) {
        System.out.println(new Par(1, 2).a);
        System.out.println(new Son(2, 2).a);
    }

}

输出结果

 

 

结论:子类在调用构造函数时,需要先调用父类的构造函数(创建一个父类),本案例中的x,y无法被继承下来,但依旧可以通过调用父类的super(x,y)给父类的x,y赋值,通过get方法在获取x,y的值

如果父类只有有参构造方法

class Person{

    int x,y;

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

    public void run(){
        System.out.println("run...");
    }
    public void eat(){
        System.out.println("eat...");
    }
}

子类的构造方法只能比父类的构造方法一样或者更多,如果建个无参那就不行了

 

posted @ 2022-12-14 17:43  谢端阳  阅读(59)  评论(0编辑  收藏  举报