Dart 使用 extends
關鍵字來繼承一個類。github
特別的是,在 Dart 中,構造函數是不能被繼承的。bash
除了默認構造函數是空參數的類,其構造函數是可以被子類自動繼承的。函數
若是子類想要調用父類的構造函數,可使用 super
關鍵字。post
class NewPoint extends Point{
NewPoint(x, y):super(x, y);
NewPoint.newOrigin():super.origin(){
print('$x, $y');
}
}
複製代碼
當調用 NewPoint.newOrigin()
時,會先調用父類的 origin
構造函數,而後再執行該構造函數內的表達式。ui
其中, NewPoint.newOrigin()
形式的構造函數被成爲 命名構造函數。this
在 Dart 中,使用 implements
關鍵字來繼承一個類。spa
它意味着子類繼承了父類的 API,但不繼承其實現。3d
不一樣於 Java,Dart 能夠直接繼承一個普通類。code
// 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()));
}複製代碼