继承
Dart 使用 extends
关键字来继承一个类。
特别的是,在 Dart 中,构造函数是不能被继承的。
除了默认构造函数是空参数的类,其构造函数是能够被子类自动继承的。
如果子类想要调用父类的构造函数,可以使用 super
关键字。
class NewPoint extends Point{
NewPoint(x, y):super(x, y);
NewPoint.newOrigin():super.origin(){
print('$x, $y');
}
}
当调用 NewPoint.newOrigin()
时,会先调用父类的 origin
构造函数,然后再执行该构造函数内的表达式。
其中, NewPoint.newOrigin()
形式的构造函数被成为 命名构造函数。
实现
在 Dart 中,使用 implements
关键字来继承一个类。
它意味着子类继承了父类的 API,但不继承其实现。
不同于 Java,Dart 可以直接继承一个普通类。
// A person. The implicit interface contains greet().
class Person {
// In the interface, but visible only in this library.
final _name;
// Not in the interface, since this is a constructor.
Person(this._name);
// In the interface.
String greet(String who) => 'Hello, $who. I am $_name.';
}
// An implementation of the Person interface.
class Impostor implements Person {
get _name => '';
String greet(String who) => 'Hi $who. Do you know who I am?';
}
String greetBob(Person person) => person.greet('Bob');
void main() {
print(greetBob(Person('Kathy')));
print(greetBob(Impostor()));
}