在子类中调用超级构造函数?

时间:2018-11-12 20:20:30

标签: java inheritance constructor subclass super

My code

如何在子类中调用超类构造函数以使此代码起作用?

class Ale {

   protected int x = 1;

   public Ale( int xx ) {
      x = xx;
   }
}  

class Bud extends Ale {

   private int y = 2;

   public void display() {
      System.out.println("x = " + x + " y = " + y);             
   }
}

1 个答案:

答案 0 :(得分:1)

您可以像这样调用超级构造函数,

class Ale {

    protected int x = 1;

    public Ale(int xx) {
        x = xx;
    }
}

class Bud extends Ale {

    Bud() {
        super(75);
    }

    private int y = 2;

    public void display() {
        System.out.println("x = " + x + " y = " + y);
    }
}