【问题标题】:Error when trying to inherit from another subclass? [duplicate]尝试从另一个子类继承时出错? [复制]
【发布时间】:2018-04-02 21:19:43
【问题描述】:
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 在没有任何构造函数的情况下工作。

【问题讨论】:

    标签: java


    【解决方案1】:

    因为Motorcycle 没有默认构造函数,所以你不能在Moped 中使用它——但你可以为Moped 添加一个空构造函数——比如,

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

    【讨论】:

      【解决方案2】:

      如果一个类没有无参数构造函数,那么每个子类都必须通过 super() 调用其中一个显式定义的构造函数。这是 Java 是一种冗长语言的示例;它不会假设它可以继承构造函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多