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

问题描述 投票:0回答:1

我不明白为什么我们需要工具?根据这个https://dart.dev/language/classes#implicit-interfaces 在使用了implements之后,我们应该重写父类中除了构造函数之外的所有内容。

// 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?';
}

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

dart oop implements
1个回答
0
投票

使用

Derived implements Base
的目的是指定
Derived
Base
遵循相同的接口。无论何时需要
Derived
对象,Base 都是 可替代的
。如果您创建了一个新的、不相关的类,那么类型系统将阻止您将该类的实例作为 
Base
传递。 (在没有静态类型的语言中,你不需要像
implements
这样的东西,因为你可以使用 ducktyping。如果你真的想要,如果你使用
dynamic
,你也可以在 Dart 中这样做。)

extends
相比,
implements
允许类提供多个不相关的接口,而不会产生真正的多重继承带来的歧义。

© www.soinside.com 2019 - 2024. All rights reserved.