This question already has answers here:
Java Constructor Inheritance
                                
                                    (10个回答)
                                
                        
                2年前关闭。
            
        

public class Vehicle {

  private double speed;
  private int wheels;

  public Vehicle() {

  }

  public Vehicle(double speed, int wheels) {
    this.speed = speed;
    this.wheels = wheels;
  }

}


public class Motorcycle extends Vehicle {

  private double engineSize;

  public Motorcycle(double speed, double engine) {
    super(speed, 2);
    this.engineSize = engine;
  }

}


public class Moped extends Motorcycle {


}


由于Mope扩展了Motorcycle,为什么会告诉我Moped需要创建构造函数?我希望Moped在没有任何构造函数的情况下工作。

最佳答案

由于Motorcycle没有默认的构造函数,因此您无法在Moped中使用它-但可以为Moped添加一个空的构造函数-例如,

public class Moped extends Motorcycle {
    public Moped() {
        super(70, 50); //<-- or whatever values you want
    }
}

07-24 09:24