Sub topic 3
Abstract classes and implicit interfaces
This chapter assumes you know Dart variables, functions, null safety, and basic class and constructor syntax. It covers how abstract classes define contracts, how mixins share behavior, and how to choose between the available reuse tools.
Abstract classes and implicit interfaces
An abstract class cannot be instantiated. Every class also defines an implicit interface: the set of its public members. Another class can implements that interface and must supply every member itself.
abstract interface class Shape {
double get area;
}
class Square implements Shape {
final double side;
Square(this.side);
@override
double get area => side * side;
}Mixins and the with clause
A mixin is a unit of reusable behavior. A class adds it with with after its superclass.
mixin Swimmer {
void swim() => print('Swimming');
}
class Animal {
final String name;
Animal(this.name);
}
class Duck extends Animal with Swimmer {
Duck(super.name);
}
void main() {
Duck('Donald').swim();
}Restricting a mixin with on
The on clause limits which classes may use a mixin. Inside the mixin, you can then call members of that required superclass.
class Animal {
final String name;
Animal(this.name);
String describe() => 'Animal $name';
}
mixin Loud on Animal {
String shout() => describe().toUpperCase();
}
class Parrot extends Animal with Loud {
Parrot(super.name);
}Class modifiers
Dart 3 modifiers control how other libraries may use a class.
| Modifier | Instantiate outside library | Extend outside library | Implement outside library |
|---|---|---|---|
| abstract | No | Yes | Yes |
| base | Yes | Yes, only with base, final, or sealed subclasses | No |
| interface | Yes | No | Yes |
| final | Yes | No | No |
| sealed | No | No | No |
Choosing between extends, implements, with, and composition
- Use
extendswhen a subclass needs the parent's code and has one parent. - Use
implementswhen you need only a contract and will write every member. - Use
withwhen several unrelated classes need the same behavior. - Use composition, meaning a field that holds another object, when behavior comes from several sources or must change at runtime.
Exercise
Exercise
What happens if you remove the on Animal clause from mixin Loud and keep the body that calls describe()?
Show answer
The compiler reports an error because describe is not defined for the mixin. The on clause tells the compiler that any class using Loud extends Animal, so describe exists.