每個類都隱式地定義一個接口,該接口包含類的所有實例成員及其實現的任何接口。如果您想創建一個類A,它支持類B的API而不繼承B的實現,那么類A應該實現B接口。
~~~
// 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()));
}
~~~
這里有一個例子,說明一個類實現多個接口:
~~~
class Point implements Comparable, Location {...}
~~~
>譯者注:仔細閱讀本章的示例代碼去理解繼承和接口實現的差別
>