Classes, Enums, Extensions
Inheritance
extends, super, override
extends makes one class inherit from another. A subclass constructor uses : super(...) to initialize inherited fields, and @override plus a same-named method replaces the parent's version. super.method() still reaches the parent body.
Program
Play the program to build a Car that extends Vehicle and overrides describe.
inheritance_extends.dart
Replay: real traced execution (multi-file project)
class Vehicle {
final String name;
final int wheels;
Vehicle(this.name, this.wheels);
String describe() => '$name has $wheels wheels';
}
class Car extends Vehicle {
final int doors;
Car(String name, this.doors) : super(name, 4);
@override
String describe() => '${super.describe()} and $doors doors';
}
void main() {
var c = Car('Sedan', 4);
print(c.describe());
}
call ← Car('Sedan', 4)
15void main() {16 var c = Car('Sedan', 4);17 print(c.describe());values this stepCar('Sedan', 4)callsuper call ← Vehicle('Sedan', 4)
9final int doors;10Car(String name, this.doors) : super(name, 4);11@overridevalues this stepVehicle('Sedan', 4)super callSedanname4this.doorsVehicle init ← name=Sedan, wheels=4
3final int wheels;4Vehicle(this.name, this.wheels);5String describe() => '$name has $wheels wheels';values this stepname=Sedan, wheels=4Vehicle initSedanthis.name4this.wheelsc ← Car(name: Sedan, wheels: 4, doors: 4)
15void main() {16 var c = Car('Sedan', 4);17 print(c.describe());values this stepCar(name: Sedan, wheels: 4, doors: 4)ccall ← c.describe()
16 var c = Car('Sedan', 4);17 print(c.describe());18}values this stepc.describe()callCar(...)ccalls ← super.describe()
11 @override12 String describe() => '${super.describe()} and $doors doors';13}values this stepsuper.describe()callsCar instancethisreturn value ← Sedan has 4 wheels
4 Vehicle(this.name, this.wheels);5 String describe() => '$name has $wheels wheels';6}values this stepSedan has 4 wheelsreturn valueSedanthis.name4this.wheelsoverride return ← Sedan has 4 wheels and 4 doors
11 @override12 String describe() => '${super.describe()} and $doors doors';13}values this stepSedan has 4 wheels and 4 doorsoverride returnprint(c.describe());
16 var c = Car('Sedan', 4);17 print(c.describe());18}outputSedan has 4 wheels and 4 doors
extends
`class Car extends Vehicle` makes `Car` inherit from `Vehicle`.
super constructor
`: super(name, 4)` forwards to the parent constructor so inherited fields are initialized.
override
`@override` plus a same-named method replaces the parent's; `super.describe()` still reaches the parent body.