Overriding
suggest changeIn Dart, subclasses can redefine methods, getters, setters, and operators inherited from their superclasses or implemented interfaces. Annotating overridden members with @override enables the Dart analyzer to verify that the member actually exists on the supertype, preventing silent typos and signature mismatches.
Overriding Methods and Calling super
When overriding an instance method, you can either replace the parent behavior completely or augment it using super.methodName():
class Vehicle {
final String model;
Vehicle(this.model);
void startEngine() {
print('Checking spark plugs and starting $model...');
}
}
class ElectricCar extends Vehicle {
final int batteryLevel;
ElectricCar(super.model, this.batteryLevel);
@override
void startEngine() {
// Override completely: electric vehicles do not have spark plugs
print('Silent power-on for $model. Battery at $batteryLevel%.');
}
}
class HybridCar extends Vehicle {
HybridCar(super.model);
@override
void startEngine() {
// Augment parent implementation
super.startEngine();
print('Electric hybrid battery initialized.');
}
}
void main() {
final tesla = ElectricCar('Model 3', 92);
tesla.startEngine();
final prius = HybridCar('Prius');
prius.startEngine();
}
Overriding Getters and Setters
Subclasses can override fields or accessors to provide custom computation, caching, or validation:
class Rectangle {
double width;
double height;
Rectangle(this.width, this.height);
double get area => width * height;
}
class Square extends Rectangle {
Square(double size) : super(size, size);
@override
set width(double value) {
super.width = value;
super.height = value; // Keep dimensions square
}
@override
set height(double value) {
super.width = value;
super.height = value;
}
}
Overriding operator == and hashCode
In Dart, every class inherits operator == and hashCode from Object. By default, == compares referential identity (memory address).
To implement value-based equality, you must override both operator == and hashCode together:
class Coordinate {
final int x;
final int y;
const Coordinate(this.x, this.y);
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is Coordinate && other.x == x && other.y == y;
}
@override
int get hashCode => Object.hash(x, y);
}
void main() {
final c1 = Coordinate(10, 20);
final c2 = Coordinate(10, 20);
print(c1 == c2); // true (value equality)
// Set and Map lookups depend on consistent hashCode:
final set = {c1};
print(set.contains(c2)); // true
}
Critical Rule: If
c1 == c2evaluates totrue, thenc1.hashCodemust equalc2.hashCode. If you override==without updatinghashCode, lookups inSetandMapcollections will fail unpredictably.
The covariant Keyword
In standard Dart typing, a subclass method parameter cannot narrow down the expected type. Marking a parameter with covariant permits narrowing the parameter type to a more specific subtype:
class AnimalFood {}
class Meat extends AnimalFood {}
class Grass extends AnimalFood {}
abstract class Animal {
void eat(covariant AnimalFood food);
}
class Lion extends Animal {
// Narrow parameter from AnimalFood to Meat using covariant
@override
void eat(Meat food) {
print('Lion eating meat.');
}
}
Overriding noSuchMethod
When an object receives a method call that it does not declare, the Dart runtime invokes noSuchMethod(Invocation invocation). Overriding noSuchMethod allows creating dynamic proxies, mocks, or flexible facades:
class DynamicProxy {
@override
dynamic noSuchMethod(Invocation invocation) {
final memberName = invocation.memberName.toString();
print('Intercepted missing call: $memberName');
return 'proxied_result';
}
}
void main() {
dynamic proxy = DynamicProxy();
final result = proxy.undefinedMethod('arg1', 42);
print('Result: $result'); // "proxied_result"
}
Best Practices
- Always annotate with
@override: Ensures the compiler alerts you immediately if the superclass method signature changes or if you make a spelling error. - Always pair
operator ==withhashCode: UseObject.hash(prop1, prop2)orObject.hashAll(list)to generate uniform hash codes. - Respect the Liskov Substitution Principle: Subclasses should honor the behavioral contracts of their parent class and not throw unexpected errors when passed into functions expecting the base type.