我不明白为什么我们需要实现,根据这个https://dart.dev/language/classes#implicit-interfaces在我们使用实现之后,我们应该重写父类中的所有内容,除了构造函数。
// A person. The implicit interface contains greet().
class Person {
// In the interface, but visible only in this library.
final String _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 {
String get _name => '';
String greet(String who) => 'Hi $who. Do you know who I am?';
}
字符串
所以我的问题实际上是为什么我们不能创建一个新的类而不是使用实现?
2条答案
按热度按时间tzdcorbm1#
使用
Derived implements Base
的目的是指定Derived
与Base
遵循相同的接口。Derived
是substitutable,无论Base
对象在哪里。如果你创建了一个新的,不相关的类,那么类型系统将阻止你将该类的示例作为Base
传递。(在没有静态类型的语言中,你不需要像implements
这样的东西,因为你可以使用duck typing。如果你真的想,你也可以在Dart中使用dynamic
。)与
extends
相反,implements
允许一个类提供 * 多个 * 不相关的接口,而不会产生真正的多重继承所带来的二义性。e3bfsja22#
如果你不进入太多的细节,并尽可能简单地看待这一切,那么在我看来,文字本身说什么就是什么。
关键字
extends
表示某个类型扩展了另一个类型的功能。也就是说,新型别会使用父型别的现有功能,而且通常会加入自己的(新)功能。
关键字
implements
的意思是某个类型实现了另一个类型声明的功能,也就是说,本质上假设继承的类型在某种程度上是抽象的。在这种情况下,这意味着可能只是缺少父类型中的功能实现。
用于
extend
新类的类型将成为新类的main supertype
。可以使用关键字
super
来访问主超类型的实现。