[Dart] Mixin

随声附和 提交于 2019-12-03 15:08:54

Docs

Mixins are a way of reusing a class’s code in multiple class hierarchies.

void main() {
  Animal animal = Animal();
  Bird().fly();  
  Fish().swim();
  Duck().move();  
  Duck().swim();
  Duck().fly();
}


mixin CanSwim {
  void swim() {
    print('change poisiton by swimming');
  }
}

mixin CanFly {
  void fly() {
    print('change poisiton by flying');
  }
}

class Animal {
  
  void move () {

    print('change position');
  }
}

class Fish extends Animal with CanSwim{
  
  @override
  void move () {
    super.move();
  }
}

class Bird extends Animal with CanFly{
  
  @override
  void move () {
    super.move();
  }
}

class Duck extends Animal with CanFly, CanSwim{
  
  @override
  void move () {
    super.move();
  }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!