为什么我们在 dart 里有工具?

gijlo24d  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(66)

我不明白为什么我们需要实现,根据这个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?';
}

字符串
所以我的问题实际上是为什么我们不能创建一个新的类而不是使用实现?

tzdcorbm

tzdcorbm1#

使用Derived implements Base的目的是指定DerivedBase遵循相同的接口。Derivedsubstitutable,无论Base对象在哪里。如果你创建了一个新的,不相关的类,那么类型系统将阻止你将该类的示例作为Base传递。(在没有静态类型的语言中,你不需要像implements这样的东西,因为你可以使用duck typing。如果你真的想,你也可以在Dart中使用dynamic。)
extends相反,implements允许一个类提供 * 多个 * 不相关的接口,而不会产生真正的多重继承所带来的二义性。

e3bfsja2

e3bfsja22#

如果你不进入太多的细节,并尽可能简单地看待这一切,那么在我看来,文字本身说什么就是什么。
关键字extends表示某个类型扩展了另一个类型的功能。
也就是说,新型别会使用父型别的现有功能,而且通常会加入自己的(新)功能。
关键字implements的意思是某个类型实现了另一个类型声明的功能,也就是说,本质上假设继承的类型在某种程度上是抽象的。
在这种情况下,这意味着可能只是缺少父类型中的功能实现。
用于extend新类的类型将成为新类的main supertype
可以使用关键字super来访问主超类型的实现。

相关问题