Dart Overriding in Depth
An override can call the parent version of its own method with super. Super parameters also shorten the constructor that passes values up.
Calling the parent version
The dog calls the animal version first, then adds its own line. Both lines print, and the parent line comes first.
class Animal {
void speak() {
print('The animal makes a sound');
}
}
class Dog extends Animal {
@override
void speak() {
super.speak();
print('The dog barks');
}
}
void main() {
var dog = Dog();
dog.speak();
}A super parameter
The super parameter sends the name straight to the parent constructor. The child class needs no field of its own and no forwarding line.
class Animal {
String name;
Animal(this.name);
}
class Dog extends Animal {
Dog(super.name);
}
void main() {
var dog = Dog('Rex');
print(dog.name);
}Replacing the behaviour
This override never calls super, so the parent line never prints. The child version is the only output.
class Animal {
void speak() {
print('The animal makes a sound');
}
}
class Cat extends Animal {
@override
void speak() {
print('The cat meows');
}
}
void main() {
var cat = Cat();
cat.speak();
}Overriding a getter
The parent exposes a label through a getter. The child overrides the getter, so the child text prints.
class Animal {
String get label => 'Animal';
}
class Dog extends Animal {
@override
String get label => 'Dog';
}
void main() {
var dog = Dog();
print(dog.label);
}Example
class Animal {
String name;
Animal(this.name);
void describe() {
print('$name is an animal');
}
}
class Dog extends Animal {
Dog(super.name);
@override
void describe() {
super.describe();
print('$name is a good dog');
}
}
void main() {
var dog = Dog('Rex');
dog.describe();
}Key points
- An override can call the parent method with super, then add its own work after it.
- When an override calls super, both versions run and the parent version runs first.
- A super parameter like Dog(super.name) sends a value straight to the parent constructor.
- The super parameter form replaces the explicit : super(name) form.
- An override can also skip super and change the behaviour completely.
- The @override annotation works on a getter as well as on a method.
In this example, the dog constructor passes the name up with a super parameter. The describe override calls the parent version first, then prints its own line.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What does super.speak() do inside an override?