mixin vs inheritance
- Dart course
- Intermediate
- Lesson 28/116
- 5 min
Learn the difference between mixin and inheritance.
mixin vs inheritance
Inheritance sets up an is-a relation: Dog extends Animal says a Dog is an Animal. A mixin sets up a can-do relation: class Bird with Flyer says a Bird can fly.
Inheritance is taken from a single base class; the subclass inherits all of its behavior and extends it. A mixin composes behavior blocks; it does not disturb the class hierarchy. Inheritance fits type relations; mixins fit adding behavior. The two can sit side by side: class Bird extends Animal with Flyer.
Which one when?
Choosing a mixin or inheritance depends on the nature of the relation. For an is-a relation pick inheritance; for a can-do relation pick a mixin.
Example: Dog extends Animal is right because a dog is an animal. Bird with Flyer is right because a bird can fly; but a bird is not a Flyer type. Wrong choice breaks code design: instead of building a subclass chain for every flight capability, the Flyer mixin is shared and applied to different classes. This avoids duplication and keeps the hierarchy lean.
Practice Combine inheritance and a mixin
Define a class named Animal; add a void breathe() { print('Breathing'); } method. Define a mixin named Flyer; add a void fly() { print('Flying'); } method. Write a class named Bird: class Bird extends Animal with Flyer { Bird(); }. In main, create an instance with var b = Bird(); and call b.breathe() and b.fly().
Starter code
// Define the Animal class and the Flyer mixin
// Write the Bird class extending Animal + Flyer
void main() {
// Create a Bird instance and call breathe() and fly()
}Sample solution
// Define the Animal class and the Flyer mixin
class Animal {
void breathe() {
print('Breathing');
}
}
mixin Flyer {
void fly() {
print('Flying');
}
}
class Bird extends Animal with Flyer {
Bird();
}
void main() {
var b = Bird();
b.breathe();
b.fly();
}Expected output
Breathing Flying
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Combine inheritance and a mixin
class Bird extends Animal ____ Flyer {
Bird();
}
class Bird extends Animal with Flyer {
Bird();
}
Explanation: with adds the mixin to the inheritance chain.
2 Which is true?
- Inheritance is an is-a relation, a mixin is a can-do relation Correct answer
- Inheritance is a can-do relation, a mixin is an is-a relation
- A mixin is only used with abstract classes
- They are the same
Explanation: Inheritance sets a type relation, a mixin sets a behavior relation; they serve different goals.
3 Match the relation types
| Term | Meaning |
|---|---|
extends |
Is-a relation |
with |
Can-do relation |
Animal |
Base class |