Dart
Multiple mixins
Learn to apply multiple mixins.
Multiple mixins
A class can apply many mixins, separated by commas. This shows Dart's power to combine behaviors; the single inheritance limit is overcome.
Example: class Duck with Flyer, Swimmer { ... }. Here the Duck class applies both the Flyer and the Swimmer mixin. Methods of both mixins are reachable on an instance: Duck().fly() and Duck().swim(). The mixin list is read left to right; the leftmost is applied first. When two mixins share a method name, the rightmost (last applied) wins.
Application order
The mixin list is applied left to right; order matters. When two mixins share a method name, the rightmost mixin wins and overrides the previous one.
Example: class A with M1, M2. Here M1 is applied first, then M2. If both define hello(), the class calls M2.hello(); M1.hello() is hidden. This behavior is how priority is set in behavior composition. Changing the order changes the results; this is why mixin list design needs care.
Exercise Apply two mixins to Duck
Define two mixins named Flyer and Swimmer. In Flyer add a void fly() { print('Flying'); } method, in Swimmer add a void swim() { print('Swimming'); } method. Write a class named Duck: class Duck with Flyer, Swimmer { Duck(); }. In main, create an instance with var d = Duck(); and call d.fly() and d.swim().
Show example solution
// Define the Flyer and Swimmer mixins
mixin Flyer {
void fly() {
print('Flying');
}
}
mixin Swimmer {
void swim() {
print('Swimming');
}
}
class Duck with Flyer, Swimmer {
Duck();
}
void main() {
var d = Duck();
d.fly();
d.swim();
}
Test yourself
-
How is class Duck with Flyer, Swimmer { } written?
- class Duck with Flyer; Swimmer { }
- class Duck extends Flyer implements Swimmer { }
- class Duck with Flyer, Swimmer { }
- class Duck with Flyer with Swimmer { }
Show answer
class Duck with Flyer, Swimmer { } — Multiple mixins are separated by commas.
-
Match the multiple mixin parts
- ,
- List separator
- Flyer, Swimmer
- Mixin list
- Duck
- Class name
-
Add the second mixin
class Duck with Flyer____ Swimmer {
Duck();
}
Show answer
class Duck with Flyer, Swimmer {
Duck();
}
Next lesson: mixin vs inheritance