The @override Annotation
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 39 of 110.
The @override annotation is a best practice marker that tells Dart (and other developers) that you're intentionally replacing a method from a parent class. While method overriding works without it, using @override adds an important safety net.
class Animal {
String name;
Animal(this.name);
void speak() {
print('$name makes a sound');
}
}
class Dog extends Animal {
Dog(String name) : super(name);
@override
void speak() {
print('$name barks: Woof!');
}
}The annotation provides two key benefits. First, it documents your intent clearly - anyone reading the code immediately knows this method exists in the parent class. Second, Dart's analyzer will warn you if the parent method doesn't actually exist, catching typos and refactoring mistakes early.
Consider what happens if you misspell the method name without @override:
class Cat extends Animal {
Cat(String name) : super(name);
void speek() { // Typo! No warning without @override
print('$name meows');
}
}Without the annotation, Dart assumes you're creating a new method called speek(). With @override, the analyzer would immediately flag that no such method exists in the parent class. This simple annotation prevents subtle bugs that can be difficult to track down later.
Challenge
EasyLet's build a media player system that demonstrates the importance of the @override annotation when customizing inherited behavior. You'll create different media types that each play content in their own way.
You'll organize your code into two files:
media.dart: Define your media hierarchy here:- A
Mediaclass with aString titleproperty, a constructor that takes the title, and a methodplay()that printsPlaying: [title] - A
Songclass that extendsMediaand adds aString artistproperty. Use the@overrideannotation and overrideplay()to printPlaying song: [title] by [artist] - A
Videoclass that extendsMediaand adds anint durationproperty (in seconds). Use@overrideand overrideplay()to first call the parent's version withsuper.play(), then printDuration: [duration] seconds
- A
main.dart: Import your media file and demonstrate the overridden methods:- Create a
Mediaobject with title'Generic Content'and callplay() - Print an empty line
- Create a
Songwith title'Imagine'and artist'John Lennon', then callplay() - Print an empty line
- Create a
Videowith title'Dart Tutorial'and duration360, then callplay()
- Create a
The @override annotation documents your intent and helps catch errors. If you accidentally misspelled play() as plya(), the annotation would alert you that no such method exists in the parent class.
Expected output:
Playing: Generic Content
Playing song: Imagine by John Lennon
Playing: Dart Tutorial
Duration: 360 secondsCheat sheet
The @override annotation marks methods that intentionally replace a parent class method. While optional, it provides safety and clarity.
class Animal {
String name;
Animal(this.name);
void speak() {
print('$name makes a sound');
}
}
class Dog extends Animal {
Dog(String name) : super(name);
@override
void speak() {
print('$name barks: Woof!');
}
}Benefits of @override:
- Documents intent - shows the method exists in the parent class
- Catches errors - Dart's analyzer warns if the parent method doesn't exist, preventing typos
Without @override, typos create new methods instead of flagging errors:
class Cat extends Animal {
Cat(String name) : super(name);
void speek() { // Typo creates new method without warning
print('$name meows');
}
}You can call the parent's version using super:
@override
void play() {
super.play(); // Call parent method first
print('Additional behavior');
}Try it yourself
import 'media.dart';
void main() {
// TODO: Create a Media object with title 'Generic Content' and call play()
// TODO: Print an empty line
// TODO: Create a Song with title 'Imagine' and artist 'John Lennon', then call play()
// TODO: Print an empty line
// TODO: Create a Video with title 'Dart Tutorial' and duration 360, then call play()
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor