给定此代码:
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");
}
根据多张单据:
- https://www.dartlang.org/dart-tips/dart-tips-ep-11.html个
- https://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#ch02-implicit-interfaces
您可以使用以下语法调用超类的构造函数:
Dog() : super("Spot");
我假设这是一种快捷语法,可以快速调用超类的构造函数.但是如果我还想在狗的构造器中做其他事情,比如调用print
,该怎么办呢.
为什么这不起作用,编写代码的正确方式是什么?
// Why does this fail
Dog() {
super("Spot");
print("Dog was created");
}