This section documents the use of classes in Dart

  • Callable class
  • Mixed Mixins
Callable class

If the Dart class implements the call() function, it can be called as a method.

class Callable {
  void call(int a, int b) {
    print(a + b);
  }
}

void main() {
  Callable callable = Callable();
  callable(10, 15);
}
Copy the code

The result is 25, and the call() method is executed directly

Mixed Mixins
  • Mixins are a way of reusing code for a class in multiple class inheritance.
  • Mixin classes cannot have constructors.
  • Usage is theWith + mixin classesClass in the following demoCThere area,bwithcThree ways.
class A {
  void a() => print("Aa");

  void b() => print("Ab");

}

class B {
  void a() => print("Ba");

  void b() => print("Bb");
}

class C with A, B {
  void c() => print("C");
}

class D with B, A {
  void d() => print("D");
}

void main() {
  C c = C();
  D d = D();
  c.a();
  d.a();
  c.b();
  d.b();
  c.c();
  d.d();
}
Copy the code
  • Since class A and class B have the same method A, the specific execution is determined by the last mixed class (that is, class B), so the running result is output Ba Aa Bb Ab C D

  • Inheritance is compatible with mixins. In the following demo, class R1 and R2 inherit class C and support MixinA class B

class A {
  void f() => print("A");
}

class B {
  void f() => print("B");
}

class C {
  void f() => print("C");
}

class R1 extends C with A, B {}

class R2 extends C with B, A {}

class R3 extends C with B, A {
  @override
  f() {
    super.f();
  }
}

void main() {
  R1 r1 = R1();
  R2 r2 = R2();
  R3 r3 = R3();
  r1.f();
  r2.f();
  r3.f();
}
Copy the code

F overrides the call to super from R2 and R3. F overrides the call to super from R2 and R3. F overrides the call to super from R3.

  • Mixins make up for the lack of interfaces and inheritance (inheritance only supports single inheritance, and interfaces cannot be reused) by mixing and reusing concrete implementations of mixed classes.

As shown in the following demo, it is possible to design an abstract class D with both a and B methods, while not having to implement b methods as C does

abstract class A {
  void a();
}

abstract class B {
  void b();
}

abstract class C extends A implements B {
  @override
  void b() => print("B");
}

abstract class D with A, B {}
Copy the code