Subtyping
- Dart course
- Expert
- Lesson 4/47
- 5 min
Learn subtyping and polymorphism.
Subtyping
Subtyping is when one type is a subtype of another. In class Dog extends Animal, Dog is a subtype of Animal. A Dog can be assigned to an Animal variable (polymorphism).
The subtype must preserve the supertype's contract: it must support its methods and behave consistently. In Dart, extends gives inheritance, implements interface implementation, and with mixin usage.
Polymorphism and override
Polymorphism is when a supertype variable can hold subtype instances. Animal a = Dog(); is valid. The @override annotation marks that a subtype redefines a supertype method: @override String speak() => 'Woof';.
Dart recommends @override; if the signature is wrong, a compile error is raised. Polymorphism lets you write code against the supertype and specialize in subtypes.
Practice Animal and Dog subtype
Define an Animal class with a String speak() => 'Sound'; method. Make Dog extend Animal and include an @override String speak() => 'Woof'; method. In main create final Animal a = Dog();; print the result with print(a.speak());.
Starter code
void main() {
// define Animal class and Dog subtype
// assign a Dog instance to a supertype variable; print speak()
}Sample solution
class Animal {
String speak() => 'Sound';
}
class Dog extends Animal {
@override
String speak() => 'Woof';
}
void main() {
final Animal a = Dog();
print(a.speak());
}Expected output
Woof
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What must a subtype satisfy?
- Must preserve the supertype's contract Correct answer
- Must have the same field names only
- Must contain fewer methods
- Must use the same constructor parameters
Explanation: a subtype must preserve the supertype's contract (Liskov substitution).
2 Match the subtyping relations
| Term | Meaning |
|---|---|
extends |
Inheritance |
implements |
Interface implementation |
with |
Mixin usage |
Dog <: Animal |
Subtype example |
3 The @override annotation
class Dog extends Animal {
@____
String speak() => 'Woof';
}
class Dog extends Animal {
@override
String speak() => 'Woof';
}
Explanation: @override marks that a method is redefined.