【问题标题】:Subclass in dart forces me to call superclass constructor飞镖中的子类迫使我调用超类构造函数
【发布时间】:2020-05-08 20:14:37
【问题描述】:

我正在使用 dart 编程语言,其中我有一个抽象类 Vehicle 和一个子类 car


abstract class Vehicle {

  int _tires;
  String _type;


  Vehicle(int tires,String type) {
    this._tires=tires;
    this._type=type;

  }
}
class car extends Vehicle {

car (int tires, String type)  {
   this._type=type;
   this._tires=tires;
  }

}

Vehicle 和 car 都在同一个库中,但我不断收到错误提示

超类“Vehicle”没有零参数构造函数。尝试在“Vehicle”中声明一个零参数构造函数,或在“Vehicle”中显式调用不同的构造函数。

为什么我不能在汽车子类中声明一个单独的构造函数?提前致谢!

【问题讨论】:

    标签: oop dart constructor


    【解决方案1】:

    由于您使用了car extends Vehicle,因此您已经声明carVehicle 的派生版本,并且应该继承Vehicle 的实现。要继承Vehicle 的实现,您实际上需要构造一个Vehicle,这需要调用基类Vehicle 的构造函数。

    如果您希望car 提供自己的、独立的实现 Vehicle,那么您应该改用car implements Vehicle。这表明car 符合Vehicle 接口,但会自行实现所有内容。请注意,这样做意味着car 需要提供自己的int _tiresString _type 成员。

    【讨论】:

    • 飞镖文档指定不继承构造函数。这意味着我应该能够提供自己的汽车构造函数,而无需构造车辆。我也不确定您所说的“要继承 Vehicle 的实现,您实际上需要构造一个 Vehicle,这需要调用 Vehicle 基类的构造函数。”
    • 不继承正确的构造函数。我说的是继承方法。假设Vehicle 实现了一些使用_tires 的公共方法go(),而car 继承了它。 Vehicle.go()如何保证_tires被初始化?目前Vehicle 做出了保证,因为Vehicle 的构造函数保证初始化它。如果派生类car 不需要调用基类构造函数,则无法保证基类成员已正确初始化。如果Vehicle 添加了go() 所依赖的一些新的(可能是私有的)数据成员怎么办?
    猜你喜欢
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 2013-10-20
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多