Dart语法之Mixins与with关键字

Dart和Java一样只支持单继承。而且Dart中没有和Java一样提供Interface字段去声明一个接口,但是也有抽象类。

如果想使用和Java接口一样的功能可以使用Mixins和implements两种方式,分别解释下两种方式:

  • Mixins : 指能够将另一个或多个类的功能添加到您自己的类中,而无需继承这些类。
  • implements : 将一个类作为接口使用
class A {
  void a() {
    print('fun a => by a');
  }
}

class B implements A {
  @override
  void a() {
    print('fun a => by b');
  }
}

class C {

  void a() {
    print('fun a => by c');
  }

  void c() {
    print('fun c => by c');
  }

  void s(){
    print('fun s => by c');
  }
}

class E {
  String e = 'eeee';

  void s(){
    print('fun s => by e');
  }
}

class D extends A with C, E {
  void c() {
    print('fun c => by d');
  }
}

void main() {
  D d = new D();
  d.a();
  d.s();
  d.c();
}

============ output ============
fun a => by c
fun s => by e
fun c => by d

首先看B implements A,所以此时A相对于B来说就是一个接口,所以他要实现B中的方法。换句话说,Dart每个类都是接口

然后看D extends A with C ,D继承于A,由于单继承特性,这个时候D不能再使用extends关键字继承其他类,但是可以使用with关键字折叠其他类以实现代码重用。当属性和方法重复时,以当前类为准。,比如以上例子就是 A => C => E => D 。

你可能感兴趣的:(Dart语法之Mixins与with关键字)