鉴于此代码:
abstract class Animal {
String name;
Animal (String this.name) {
}
}
class Dog extends Animal {
// Why does this fail
Dog() {
super("Spot");
print("Dog was created");
}
// Compared to this
// Dog() : super("Spot");
}
根据多个文档:
您可以使用以下语法调用父类(super class)的构造函数:
Dog() : super("Spot");
我认为这是一种快速调用父类(super class)构造函数的快捷语法。但是如果我还想在 Dog 的构造函数中做一些额外的事情,比如调用
print
.为什么这不起作用,编写代码的正确方法是什么?
// Why does this fail
Dog() {
super("Spot");
print("Dog was created");
}
最佳答案
在 Flutter (Dart) 中,如果我们有一个
class Bicycle {
int gears;
Bicycle(this.gears); // constructor
}
和一个继承它的 child class ElectricBike extends Bicycle {
int chargingTime;
}
我们可以通过父构造函数入参gears
像这样:class ElectricBike extends Bicycle {
int chargingTime;
ElectricBike(int gears, this.chargingTime) : super(gears);
}
请注意使用 : super(<parents parameters)
.
关于class - 如何在 Dart 中调用父类(super class)的构造函数和其他语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21033398/