What is the difference between `extends`, `implements` and `with` (mixins) in Dart?
Show answer — try answering out loud first
extends inherits from a single parent class and reuses its code. implements forces you to re-implement the entire contract of a class or interface, without inheriting its code. with (mixins) lets you reuse code from several classes without traditional multiple inheritance. Dart doesn't have multiple inheritance of classes, but mixins fill that gap.
extends: classic inheritance. You reuse the parent's implementation and can override (@override) whatever you want. You can only extend one class.implements: you use a class as an interface. You commit to implementing all of its methods and properties from scratch; you inherit no code. You can implement several.with(mixin): you inject the methods and properties of amixininto your class. It's Dart's way of sharing code between classes without an inheritance hierarchy. You can combine several mixins.
class Animal {
void breathe() => print("Breathing...");
}
// Mixin: reusable code to "inject"
mixin Swimmer {
void swim() => print("Swimming...");
}
mixin Flyer {
void fly() => print("Flying...");
}
// extends (inherits code) + with (mixes in mixins)
class Duck extends Animal with Swimmer, Flyer {
void introduce() => print("I'm a duck");
}
// implements: forces you to reimplement the whole contract
class Robot implements Swimmer {
@override
void swim() => print("Swimming with motors");
}
void main() {
final duck = Duck();
duck.breathe(); // inherited from Animal
duck.swim(); // from the Swimmer mixin
duck.fly(); // from the Flyer mixin
duck.introduce();
Robot().swim(); // "Swimming with motors"
}
Using implements when you actually wanted to reuse code. With implements you inherit nothing: if you implement a class with 10 methods, you have to write all 10, even if you only care about changing one. If what you want is to reuse the existing implementation, use extends or a with mixin.
"
extendsis regular inheritance: I reuse the parent's code and can only extend one class.implementstreats the class as an interface and forces me to implement its entire contract from scratch, without inheriting code, but I can implement several. Andwithinjects mixins, which are Dart's way of sharing code between classes without multiple inheritance. A typical example is a widget that useswith SingleTickerProviderStateMixinto have animations."
If a class does class Cat extends Animal implements Pet with Playful, what is the correct order of the keywords?
See answer
The correct order is: extends, then with, and finally implements:
class Cat extends Animal with Playful implements Pet { }
Order matters in Dart: first what you inherit from, then what you mix in, and finally what contracts you implement.