Sub topic 11
Inheritance, `super`, and super parameters
This chapter assumes basic Dart syntax, null safety, functions, and object-oriented terms such as class, object, and method. You will use these ideas to reuse behavior between related classes.
Extending a class
Inheritance is a relationship in which one class receives members from another class. The class being extended is the superclass. The new class is the subclass. Dart allows a class to extend only one superclass.
Use extends when the subclass is a specialized form of the superclass. A Dog is an Animal, so Dog can extend Animal.
class Animal {
final String name;
Animal(this.name);
String describe() => 'Animal $name';
void makeSound() {
print('$name makes a sound');
}
}
class Dog extends Animal {
final String breed;
Dog(super.name, this.breed);
@override
String describe() => '${super.describe()} ($breed)';
@override
void makeSound() {
print('$name barks');
}
}
void main() {
final dog = Dog('Milo', 'Labrador');
print(dog.name);
print(dog.describe());
dog.makeSound();
}Dog inherits the name field and the describe and makeSound methods. It also adds its own breed field.
The @override annotation documents that a method replaces an inherited method. The analyzer can warn you if the method does not actually override a superclass member.
Calling superclass constructors and methods
A subclass constructor must initialize the superclass before the subclass is ready. The expression Dog(super.name, this.breed) is a super parameter. It forwards the first argument directly to Animal's name parameter.
The older equivalent is:
Dog(String name, this.breed) : super(name);A super parameter is shorter, but both forms have the same effect.
Use super.method() to call the superclass implementation from an overridden method. In the example, super.describe() produces Animal Milo. The subclass then adds the breed.
Constructor work follows this order:
- Arguments are evaluated.
- The superclass constructor runs.
- The subclass fields and constructor body are initialized.
A subclass cannot directly access a superclass member marked with a leading underscore if that member belongs to another library. Public members remain available unless the subclass hides or overrides them.
When inheritance fits
Inheritance is useful when the subtype truly satisfies the superclass contract. Code that accepts an Animal should be able to use a Dog without needing to know every detail of Dog.
Avoid extending a class only to reuse a few unrelated methods. Composition is often clearer in that case: store an object in a field and delegate selected work to it. Also remember that overriding can change behavior in surprising ways. Keep inherited contracts stable, and use @override so accidental method mismatches are easier to find.
Exercise
What does Dog(super.name, this.breed) do?
Show answer
It initializes Dog's breed field and forwards the name argument to Animal's constructor through a super parameter.