The @override
annotation checks if the method name and signature in the subclass match a method in the superclass. If they match correctly, the method will be considered as an override, and it will execute when called on an instance of the subclass. If there is no matching method in the superclass, an error will be thrown during compilation.
The @override
annotation compares the method name, return type, and parameters of the method in the subclass with the method in the superclass. If any of these elements don't match exactly, the compiler will raise an error.
Here's an example to illustrate this behavior:
class ParentClass {
void displayName(){
print("Inside the Parent class Method");
}
}
class ChildClass extends ParentClass {
void displayName(){
print("Inside the Child class Method");
}
}
void main(){
ParentClass pClassObject = new ParentClass();
ChildClass cClassObject = new ChildClass();
pClassObject.displayName();
cClassObject.displayName();
}
Output
Inside the Parent class Method
Inside the Child class Method
It is not mandatory to put the @override
annotation above an overriding method in Dart. The Dart language allows you to override methods in subclasses even without explicitly using @override
.
However, it is considered a best practice to include @override
as a form of documentation and to make your code more readable and maintainable. By using @override
, you explicitly indicate your intention to override a method from the superclass, making it clear to other developers and improving code clarity.