Home > OS >  Does Dart support multiple inheritance?
Does Dart support multiple inheritance?

Time:03-17

What are the mechanisms for multiple inheritance supported by Dart?

Note: This is not a specific "Please help me get past my particular problem of the moment" style "question", but rather an actual question about the Dart programming language.

CodePudding user response:

No, Dart does not support multiple implementation inheritance.

Dart has interfaces, and like most other similar languages it has multiple interface inheritance.

For implementation, there is only a single super-class chain that a class can inherit member implementations from.

Dart does have mixins, which allows implementation to be used by multiple classes, but not through inheritance as much as by mixin application.

Example:

class A {
  String get foo;
}
class A1 implements A {
  String get foo => "A1";
}
class A2 implements A {
  String get foo => "A2";
}
mixin B on A {
  String get foo => "B:${super.foo}";
}
class C extends A1 with B {
  String get foo => "C:${super.foo}";
}
class D extends A2 with B {
  String get foo => "D:${super.foo}";
}
void main() {
  print(C().foo); // C:B:A1
  print(D().foo); // D:B:A2
}

Here the same member, B.foo, is mixed into two different classes, with two different super-classes.

Each of the classes C and D has only a single superclass chain. The superclass of C is the anonymous mixin application class A1 with B, the superclass of D is the distinct mixin application class A2 with B. Both of these classes contain the mixin member B.foo.

Mixins are not multiple inheritance, but it's the closest you'll get in Dart.

  •  Tags:  
  • dart
  • Related