Dart Mixins vs Java Inheritance

Coming from Java, I was always thinking like this “One class can extend only one class”. If I need more behavior, I need to use interfaces. Then, when I started Dart, I got confused again 😅 'extends' felt familiar, just like Java: If Dog extends Animal → Dog automatically gets eat(), sleep() from Animal So no confusion here. It’s simple inheritance. But then I saw “with … mixins” the inheritance things changed for me. Mixin in Dart = reuse behavior hastily Example: “class Dog extends Animal with Run, Swim” Now Dog can run AND swim without needing inheritance 'Run' and 'Swim' Here, Dog != Run, also Dog !=Swim still 'Dog' can access methods of Run and Swim. This is the power of 'Mixin' Also in Java, multiple inheritance is not allowed, to do that I would use interfaces and default methods for this. But in Dart I can indirectly use methods from multiple classes through mixins. Also in mixins, I can define that which class can access my mixin class by 'on' keyword. This is one of the interesting power mixin has, where normal interface implementation do not have such type of restriction power. That’s the difference, the simple way I understand now: extends = what the object is. mixin = what the object can do. #Flutter #Dart #Java #Mixin #OOP #LearningInPublic

  • graphical user interface

To view or add a comment, sign in

Explore content categories