@override
- Dart course
- Intermediate
- Lesson 78/116
- 5 min
Learn the @override annotation.
@override in depth
@override states that a subclass method redefines a superclass method. For example inside class Cat extends Animal you add @override to the String toString() method.
The annotation is not required but Dart recommends it. If you write a wrong signature the compiler warns thanks to @override; a warning appears when no matching method exists in the superclass.
It is commonly used to override Object methods such as toString, hashCode and noSuchMethod.
Practice Cat and @override
Define an Animal class with a String name field and an Animal(this.name) constructor. Write a Cat extends Animal subclass with a Cat(String name) : super(name) constructor. Add a @override method String toString() => 'Cat $name'. In main print a Cat('Luna') instance with print.
Starter code
// Define the Animal class (name, constructor)
// Define the Cat subclass, redefine toString
void main() {
// create a Cat and print it
}Sample solution
class Animal {
String name;
Animal(this.name);
}
class Cat extends Animal {
Cat(String name) : super(name);
@override
String toString() => 'Cat $name';
}
void main() {
print(Cat('Luna'));
}Expected output
Cat Luna
Analysis and @override
When you write @override Dart analysis looks for a matching method in the superclass. If it finds none it warns. This stops you from accidentally creating a new method through a typo.
For example if you write toStrring, without @override this becomes a new method; with @override analysis catches it.
A good habit: always write @override when redefining a superclass method. IDEs add it automatically.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The @override tag
class Cat extends Animal {
@____
String toString() => 'Kedi';
}
class Cat extends Animal {
@override
String toString() => 'Kedi';
}
Explanation: The word marking an override is override.
2 When is @override written?
- When adding a new method
- When deleting a field
- When redefining a superclass method Correct answer
- When setting up a loop
Explanation: @override is written when redefining a superclass method.
3 What happens if you omit @override?
- The compiler always errors
- The program does not compile
- The method does not run
- A wrong signature warning is missed Correct answer
Explanation: @override catches a wrong signature, otherwise the warning is missed.