pamphlet
pamphlet

Reputation: 2104

Does Dart support multiple inheritance?

What are the mechanisms for multiple inheritance supported by Dart?

Upvotes: 7

Views: 11693

Answers (2)

lrn
lrn

Reputation: 71623

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 another anonymous 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.

Upvotes: 13

Kira Resari
Kira Resari

Reputation: 2420

Actually, it's quite easy. The only thing that needs to be understood is that Interfaces are not defined explicitly. Instead, Dart automatically creates Interfaces for all classes. That means you can implement a class like you would implement an interface. For pure Interfaces, there's abstract classes.

Here is how that works:

abstract class TestInterfaceA{
  String getStringA();
}

abstract class TestInterfaceB{
  String getStringB();
}

class TestInterfaceImplementer implements TestInterfaceA, TestInterfaceB{
  @override
  String getStringA() {
    return "A";
  }

  @override
  String getStringB() {
    return "B";
  }
}

main(){
  test("TestInterfaceImplementer should be able to call method from TestInterface A", () {
    TestInterfaceA testInterfaceA = TestInterfaceImplementer();

    expect(testInterfaceA.getStringA(), "A");
  });
  test("TestInterfaceImplementer should be able to call method from TestInterface B", () {
    TestInterfaceB testInterfaceB = TestInterfaceImplementer();

    expect(testInterfaceB.getStringB(), "B");
  });
}

Upvotes: 1

Related Questions