Sub topic 11
Inheritance, super, and super parameters
This chapter assumes you can write a basic Dart class with fields, methods, and generative constructors, and that you know initializing formals (this.x) and initializer lists. It covers how extends works, how a subclass constructor reaches its superclass constructor, and how super parameters remove most of the forwarding boilerplate.
What extends gives you
A class declares its superclass with extends. The subclass inherits the superclass's instance members: fields, methods, getters, and setters. Dart has single inheritance, so a class has exactly one superclass. A class with no extends clause extends Object.
class Animal {
final String name;
Animal(this.name);
String describe() => 'Animal $name';
}
class Dog extends Animal {
final String breed;
Dog(super.name, this.breed);
@override
String describe() => '${super.describe()} ($breed)';
}
void main() {
print(Dog('Rex', 'Beagle').describe());
}This prints Animal Rex (Beagle). Three things are happening:
@overridetells the analyzer thatdescribereplaces an inherited method. It reports an error if nothing is being overridden, which catches typos and renamed superclass methods.super.describe()calls the superclass version of the method. Use it when you want to extend the inherited behavior and not replace it.Dog(super.name, this.breed)is a super parameter, explained below.
An overriding member must be compatible with the member it replaces. It must accept at least the same arguments, and its return type must be a subtype of the original. Getters, setters, and methods can be overridden. A field can be overridden by a getter, and an overriding field also replaces the inherited getter.
Constructors are not inherited
A subclass does not inherit any constructor from its superclass, including named constructors. If Animal has Animal.stray(), Dog.stray() does not exist until you write it. Every subclass constructor must make sure a superclass constructor runs.
If you do not call one explicitly, Dart inserts an implicit call to the superclass's unnamed, zero-argument constructor. This is where the most common error in this area comes from.
class Account {
final int id;
Account(this.id);
}
class SavingsAccount extends Account {
final double rate;
SavingsAccount(this.rate); // Error
}The analyzer reports that the superclass Account has no zero-argument constructor. The implicit super() call has nothing to match, so you must call Account(id) yourself.
The super call in the initializer list
The explicit form puts super(...) at the end of the initializer list. It can name the unnamed constructor or a named one, such as super.named(...).
class Account {
final int id;
Account(this.id);
Account.guest() : id = -1;
}
class SavingsAccount extends Account {
final double rate;
SavingsAccount(int id, this.rate) : super(id);
SavingsAccount.guest()
: rate = 0,
super.guest();
}The super call must be the last item in the initializer list. The initializer list also cannot read this, because the object is not ready yet. You can call static methods or use the constructor's own parameters there.
Order of execution
Construction runs in a fixed order. Dart initializes the subclass's fields from its initializer list first, then runs the superclass constructor (its initializer list, then its body), and finally runs the subclass constructor body.
class Base {
final String label;
Base(this.label) {
print('Base body: $label');
}
}
class Derived extends Base {
final int size;
Derived(String text, int size)
: size = _check(size),
super(text.trim()) {
print('Derived body: $size');
}
static int _check(int value) {
print('Derived initializer');
return value;
}
}
void main() {
Derived(' a ', 3);
}The output is:
Derived initializer
Base body: a
Derived body: 3This order explains a common design rule. Fields that the subclass declares are set before the superclass body runs. Any superclass body that calls an overridden method will therefore see the subclass's final fields already set. Dart does not leave them as default values the way some languages do. Even so, avoid calling overridable methods from a constructor body, because the subclass's own constructor body has not run yet.
Super parameters
Forwarding arguments to the superclass is repetitive. Before Dart 2.17, Dog(String name, this.breed) : super(name); was the standard form. A super parameter writes super.name in the subclass's parameter list, and Dart passes that value to the matching superclass parameter.
- A positional super parameter is passed to the superclass's positional parameters in order.
- A named super parameter is passed to the superclass parameter with the same name.
- If you leave out the type, it is taken from the superclass parameter. If you write one, it must be a subtype of the superclass parameter's type.
Super parameters can be mixed with ordinary parameters and initializing formals:
class Widget {
final String name;
final String? key;
Widget(this.name, {this.key});
}
class Button extends Widget {
final void Function() onTap;
Button(super.name, this.onTap, {super.key});
}Button('ok', () {}, key: 'a') passes 'ok' and 'a' to Widget. The call super(...) is implied, and you do not write it.
Two rules limit how super parameters combine with an explicit super(...) call:
- If the explicit
super(...)call passes positional arguments, you cannot also use positional super parameters. The positional arguments would be assigned twice. - Named super parameters can be combined with an explicit call, as long as you do not pass the same name twice.
class Base {
final int id;
final String? tag;
Base(this.id, {this.tag});
}
class Child extends Base {
Child({super.tag}) : super(0);
}Child(tag: 'x') creates a Base with id 0 and tag 'x'. Here the positional argument comes from the explicit call and the named one comes from the super parameter.
| Form | Example | Use it when |
|---|---|---|
| Implicit | `Dog();` | The superclass has an unnamed constructor with no required arguments. |
| Super parameter | `Dog(super.name)` | You forward a value unchanged. |
| Explicit call | `Dog(String n) : super(n.trim())` | You must transform or compute the argument. |
| Named super call | `Dog.guest() : super.guest()` | You need a specific named superclass constructor. |
Calling super in other members
super.member works in instance methods, getters, and setters, and it always refers to the superclass's implementation. It does not work in static members, which belong to the class and not an instance. Dart has no way to skip a level and call a grandparent's version of a method.
class Counter {
int value = 0;
void reset() => value = 0;
}
class LoggingCounter extends Counter {
@override
void reset() {
print('Resetting from $value');
super.reset();
}
}Common mistakes
- Forgetting
super(...)when the superclass has no zero-argument constructor. - Placing
super(...)anywhere but last in the initializer list. - Using a positional super parameter together with explicit positional arguments in
super(...). - Expecting named constructors to be inherited.
- Overriding a method with an incompatible signature, such as removing an optional parameter.
Dart 3 class modifiers such as final, interface, and sealed can forbid extends from other libraries. A later chapter covers them. This chapter's examples use plain classes, which any library can extend.
Exercise
Given class Vehicle { final String id; final int wheels; Vehicle(this.id, {this.wheels = 4}); }, write a subclass Bike whose constructor takes only the id, always passes 2 for wheels, and prints 'Bike ready' after construction. Which parts run first?
Show answer
class Bike extends Vehicle { Bike(super.id) : super(wheels: 2) { print('Bike ready'); } } The Bike initializer list has no field initializers here, so the Vehicle constructor runs first (its initializer list and then its body), and the Bike body prints last. The named argument wheels: 2 is passed explicitly, and the positional id comes from the super parameter. This is allowed because the explicit call passes no positional arguments.
Exercise
Why does class B extends A { B(int x); } fail to compile when A is declared as class A { A(int x); }, and how do you fix it in one line using a super parameter?
Show answer
B has no explicit super call, so Dart inserts an implicit super() with no arguments, but A has no zero-argument constructor. Fix it by declaring B(super.x); which forwards the value to A's constructor.