关于super-class和继承

About super-class and inheritance

void main() {
  Car myNormalCar = Car(20);

  print(myNormalCar.numberOfSeat);

  myNormalCar.drive('academia');
}

class Car {
  int numberOfSeat = 40;
  int height = 30;

  Car(int seat) {
    numberOfSeat = seat;
  }

  void drive(String name) {
    print('the wheels turn:$name');
  }
}

class ElectricCar extends Car {}

这里的ElectricCar表示"The superclass 'Car' doesn't have a zero argument constructor"。我想为从 Car for Electric 继承的属性分配不同的值 Car.How 我可以这样做吗?

您需要在 ElectricCar 中调用 Car 的构造函数,因为您是从 Car 扩展的。我不确定你到底想要什么,但你可以,例如如果您想向 ElectricCar 添加更多属性但仍希望能够设置 numberOfSeat:

,请执行以下操作
class ElectricCar extends Car {
  int power;

  ElectricCar(this.power, int seat) : super(seat);
}

重要的是你需要用 ElectricCar 的构造函数调用 Car 的构造函数,因为 Car 的构造函数是知道如何初始化 Car ElectricCar.

的一部分