Override
- Dart course
- Intermediate
- Lesson 9/116
- 5 min
Learn to redefine methods with @override.
@override
A subclass can redefine a method of its base class. This is called override and Dart suggests marking it with the @override annotation.
Example: class Dog extends Animal { @override void speak() { print('Woof woof'); } }. Here Dog replaces Animal's speak with its own version. The @override annotation is not a comment; it tells the compiler your intent. A wrong signature gives an error, so it is a safe marker. The call dispatches by the instance type: Dog().speak() prints 'Woof woof'.
Polymorphism
A base class reference can hold subclass instances. The call dispatches by the actual type of the instance; this behavior is called polymorphism.
Example: Animal a = Dog(); a.speak();. Here a has the static type Animal and the dynamic type Dog. The speak() call runs the Dog version. This lets a list hold different subclass instances and each runs its own speak() version. Polymorphism keeps code flexible and extensible.
Practice Override speak in Dog
Keep the existing Animal class. Add an @override void speak() { print('Woof woof'); } method to the Dog class. In main, create an instance with var d = Dog(); and call d.speak().
Starter code
class Animal {
void speak() {
print('Makes a sound');
}
}
class Dog extends Animal {
Dog();
// Override speak with @override
}
void main() {
// Create a Dog() instance and call speak()
}Sample solution
class Animal {
void speak() {
print('Makes a sound');
}
}
class Dog extends Animal {
Dog();
@override
void speak() {
print('Woof woof');
}
}
void main() {
var d = Dog();
d.speak();
}Expected output
Woof woof
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the override parts
| Term | Meaning |
|---|---|
@override |
Annotation |
speak |
Redefined method |
Dog |
Subclass |
2 Add the @override annotation
class Dog extends Animal {
____
void speak() {
print('Woof woof');
}
}
class Dog extends Animal {
@override
void speak() {
print('Woof woof');
}
}
Explanation: @override is written in lowercase and placed before the method signature.
3 What does Animal a = Dog(); a.speak(); print?
- Woof woof Correct answer
- Nothing
- Makes a sound
- Throws an error
Explanation: Polymorphism runs the Dog version.