Why do we have implements in dart?

87 views Asked by At

I can't get a clue why do we need implements? According to this https://dart.dev/language/classes#implicit-interfaces After we used implements we should rewrite everything we have in parent class except constructor.

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

So my question actually is why can't we just create a new class instead of use implements?

2

There are 2 answers

0
jamesdlin On BEST ANSWER

The point of using Derived implements Base is to specify that Derived conforms to the same interface as Base. Derived is substitutable wherever a Base object is expected. If you instead created a new, unrelated class, then the type system would prevent you from passing an instance of that class as a Base. (In languages that do not have static typing, you would not need something like implements since you instead could use duck typing. If you really wanted, you could do that in Dart too if you used dynamic.)

In contrast to extends, implements allows a class to provide multiple unrelated interfaces without the ambiguity that can come from true multiple inheritance.

0
mezoni On

If you don't go into too much detail and look at it all as simply as possible, then it seems to me that the words themselves say what is what.

The keyword extends means that a certain type extends the functionality of another type.
That is, a new type uses existing functionality of the parent type and usually adds its own (new) functionality.

The keyword implements means that a certain type implements the declared functionality of another type. That is, in essence, it is assumed that the inherited type is abstract to some extent.
In this case, this implies that the implementation of the functionality in the parent type may simply be missing.

The type that is used to extend the new class becomes the main supertype for the new class.
The implementation of the main supertype can be accessed using the keyword super.