Dart Inheritance
Inheritance lets a class reuse and specialise another class. A subclass declared with extends inherits all the superclass's fields and methods, can add new ones, and can override existing behaviour. Dart supports single inheritance: a class extends exactly one superclass (implicitly Object). For sharing code from several sources you'll use mixins and interfaces.
extends and super
class Vehicle {
final String plate;
int speed = 0;
Vehicle(this.plate);
void accelerate(int amount) {
speed += amount;
}
String describe() => '$plate at $speed km/h';
}
class Truck extends Vehicle {
final double loadTons;
Truck(super.plate, this.loadTons); // super parameter
@override
void accelerate(int amount) {
// heavy trucks speed up at half the rate
super.accelerate(amount ~/ 2);
}
@override
String describe() => '${super.describe()}, carrying $loadTons t';
}
void main() {
final car = Vehicle('51A-123');
final truck = Truck('29C-888', 7.5);
car.accelerate(60);
truck.accelerate(60);
print(car.describe());
print(truck.describe());
}51A-123 at 60 km/h
29C-888 at 30 km/h, carrying 7.5 t
| Keyword | Meaning |
|---|---|
extends |
Inherit implementation from one superclass |
super.x (parameter) |
Forward a constructor argument to the superclass |
super.method() |
Call the superclass's version of a method |
@override |
Annotation stating you intend to override (the linter checks it) |
Polymorphism
A variable of the superclass type can hold any subclass instance. Calling a method runs the overriding version for the actual object — that's dynamic dispatch:
class Shape {
String get name => 'shape';
double area() => 0;
}
class Square extends Shape {
final double side;
Square(this.side);
@override
String get name => 'square';
@override
double area() => side * side;
}
class Triangle extends Shape {
final double base, height;
Triangle(this.base, this.height);
@override
String get name => 'triangle';
@override
double area() => base * height / 2;
}
void main() {
final List<Shape> shapes = [Square(3), Triangle(4, 5), Shape()];
for (final s in shapes) {
print('${s.name}: ${s.area()}');
}
final total = shapes.fold(0.0, (sum, s) => sum + s.area());
print('total: $total');
}square: 9.0
triangle: 10.0
shape: 0.0
total: 19.0
The loop doesn't know or care about concrete types — adding a Circle later requires no changes there.
Constructors aren't inherited
Each class declares its own constructors. A subclass constructor must call a superclass constructor — implicitly the unnamed no-argument one, or explicitly with super(...) / super.param:
class Person {
final String name;
Person(this.name) {
print('Person($name) created');
}
Person.anonymous() : this('anonymous');
}
class Student extends Person {
final String school;
Student(super.name, this.school) {
print('Student at $school created');
}
Student.guest(this.school) : super.anonymous();
}
void main() {
Student('Thanh', 'HCMUT');
print('---');
Student.guest('Open Class');
}Person(Thanh) created
Student at HCMUT created
---
Person(anonymous) created
The superclass constructor body always runs before the subclass body.
Type checks and casting down
is checks whether an object is an instance of a type (including subtypes). Inside an if, Dart promotes the variable so you can use subclass members:
class Animal {
String sound() => '...';
}
class Cat extends Animal {
@override
String sound() => 'meow';
void purr() => print('purrr');
}
void main() {
Animal pet = Cat();
print(pet.sound());
print(pet is Animal);
print(pet is Cat);
if (pet is Cat) {
pet.purr(); // promoted to Cat
}
}meow
true
true
purrr
Overriding rules
- Parameter types may be the same or wider; return types the same or narrower (covariant returns).
- You can override fields with getters (and vice versa).
- Override
toString,==andhashCodefromObjectto customise printing and equality. - To prevent subclassing entirely, use the
finalclass modifier — see Class Modifiers.
Tip: Prefer composition (a class has another object) over deep inheritance trees. Inheritance is best when there's a true is-a relationship and the subclass genuinely specialises behaviour.
Test yourself
How many classes can a Dart class extend directly?
- None
- Exactly one
- Up to two
- Any number
Inside an overriding method, how do you call the parent's version?
- parent.method()
- super.method()
- base.method()
- this.super()
Which constructor body runs first when creating a subclass instance?
- The subclass body
- The superclass body
- They run in parallel
- Whichever is declared first in the file