Home > database >  when should add mixin keyword in dart OOP
when should add mixin keyword in dart OOP

Time:09-11

i have here two examples, both of them are works well:

    class A {
     int sum(){}
    }

   class B with A {}

and

 mixin A {
     int sum(){}
    }

   class B with A {}

what is the difference ?

CodePudding user response:

after some searches, I found only one important difference between a regular class and using mixin keyword...

the class with mixin keyword cannot be instantiated.

which means we cannot create an object from it

CodePudding user response:

Mixin is class that contains method which can be used by other class without and parent-child relation.

As per wikipedia, mixin is "include" Instead of "inherit".

  1. Mixin encourage code reusability.

  2. no parent to child relationship

  3. it's not inheritance so remove the ambiguity of multiple inheritance.

Note: don't include many mixin in one class because it is difficult to distinguish which method is from which mixin.

Q) What if two or more included mixin have method with name name?

A) Then the last mixin's having same method will run (tried in dart).


But i still don't get why we need mixin when we have static methods. And when to use what.

  • Related