When to use mixins and when to use interfaces in Dart?

后端 未结 6 2056
眼角桃花
眼角桃花 2020-12-07 19:28

I\'m very familiar with the concepts of interfaces and abstract classes, but not super familiar with the concepts of mixins.

Right now, in Dart, every clas

6条回答
  •  星月不相逢
    2020-12-07 19:38

    The difference lies in the concept. If you understand this, you will use it in the right way.

    1. In OOP, an interface is something that enforces the deriving class to implement a set list of public fields and methods.

    But unlike other traditional programming languages like C# and JAVA, Dart does not have explicit interface types. Each class, by default, defines its own interface composed of public fields and methods. So, every class can act as an interface in Dart.

    implements keyword is to implement an interface. Also, a class can implement multiple interfaces.

    1. In OOP, inheritance implies sharing of behavior between classes. We can not share features with an interface. So, when we implement a class, we can not share its behavior.

    If you want to share the behavior across these two classes, you should use the extends keyword.

    1. In OOP, a mixin is a class that contains methods for use by other classes. Unlike the interface and inheritance approach, a mixin doesn’t have to be the parent class of those other classes.

    So a mixin neither imposes usage restriction nor forces type restriction.

    You will usually put common functions inside a mixin. Make use of the mixin by using the with keyword.

    Taken from here

提交回复
热议问题