Inheritance
suggest changeDart is an object-oriented language with single inheritance. Every class has exactly one superclass, and everything ultimately inherits from Object (or Object? when nullability is considered). On top of that, Dart gives you three more tools for sharing behavior and types:
extendscreates a subclass that inherits implementation from one superclass.implementsmakes a class satisfy the interface of one or more other classes, without inheriting any code.withmixes in reusable bundles of members (mixins).
Since Dart 3, class modifiers (abstract, base, interface, final, sealed, mixin) control which of these operations other libraries are allowed to perform on your classes.
This article covers all of them. For details on redefining inherited members see Overriding, and for constructor syntax see Constructors.
Extending a class
Use extends to create a subclass. The subclass inherits all instance fields, getters, setters and methods of the superclass and can add new ones:
class Animal {
final String name;
Animal(this.name);
void eat() => print('$name is eating');
String describe() => 'an animal called $name';
}
class Dog extends Animal {
final String breed;
Dog(super.name, this.breed);
void bark() => print('$name says woof');
}
void main() {
final dog = Dog('Rex', 'beagle');
dog.eat(); // inherited from Animal
dog.bark(); // defined in Dog
print(dog.describe());
print(dog.breed);
}
Output:
Rex is eating
Rex says woof
an animal called Rex
beagle
A Dog is also an Animal, so it can be used anywhere an Animal is expected:
void feed(Animal a) => a.eat();
void main() {
feed(Dog('Rex', 'beagle')); // Rex is eating
}
Calling the superclass constructor
Constructors are not inherited. Every subclass constructor must call a superclass constructor, either implicitly or explicitly.
If you don't write a call, Dart calls the superclass's unnamed, no-argument constructor. If the superclass doesn't have one, you get a compile error and must call a constructor yourself.
There are two ways to pass arguments up.
Super parameters (Dart 2.17+) are the shortest form. super.name declares a parameter and forwards it to the superclass constructor:
class Dog extends Animal {
final String breed;
Dog(super.name, this.breed);
}
An explicit super(...) call in the initializer list is needed when you have to compute the value or call a named superclass constructor:
class Animal {
final String name;
Animal(this.name);
Animal.unknown() : name = 'unknown';
}
class Cat extends Animal {
final int lives;
// Transform the argument before passing it up.
Cat(String name) : lives = 9, super(name.toUpperCase());
// Call a named superclass constructor.
Cat.stray() : lives = 9, super.unknown();
}
void main() {
print(Cat('tom').name); // TOM
print(Cat.stray().name); // unknown
}
The super(...) call must be the last entry in the initializer list.
Super parameters also work with named parameters. This pattern is everywhere in Flutter:
class Widget {
final String? key;
const Widget({this.key});
}
class Button extends Widget {
final String label;
const Button({super.key, required this.label});
}
void main() {
final b = Button(key: 'ok', label: 'OK');
print('${b.key} ${b.label}'); // ok OK
}
Initialization order
When you construct a subclass instance, Dart runs things in this order:
- The subclass's field initializers, initializing formals (
this.x) and initializer list. - The superclass's field initializers and initializer list.
- The superclass constructor body.
- The subclass constructor body.
class Base {
Base() {
print('Base body, describe() = ${describe()}');
}
String describe() => 'base';
}
class Derived extends Base {
final String name;
Derived(this.name) {
print('Derived body');
}
@override
String describe() => 'derived $name';
}
void main() {
Derived('x');
}
Output:
Base body, describe() = derived x
Derived body
Because name is initialized before the superclass constructor body runs, the overridden describe() called from Base sees a fully initialized final field. This is different from Java or C#, where such a call can see default values. Even so, calling overridable methods from a constructor is fragile and best avoided.
Overriding and super
A subclass can replace an inherited member by declaring one with the same name. Mark it with @override so the analyzer catches typos and signature mismatches. Use super.member to call the superclass version:
class Animal {
final String name;
Animal(this.name);
String describe() => 'an animal called $name';
@override
String toString() => 'Animal($name)';
}
class Dog extends Animal {
Dog(super.name);
@override
String describe() => '${super.describe()}, which is a dog';
@override
String toString() => 'Dog($name)';
}
void main() {
final Animal a = Dog('Rex');
print(a.describe());
print(a);
}
Output:
an animal called Rex, which is a dog
Dog(Rex)
Even though the static type of a is Animal, the method that runs is chosen by the runtime type (Dog). This is dynamic dispatch, and it's what makes polymorphism work. See Overriding for getters, setters, operators and covariant parameters.
Polymorphism with abstract classes
An abstract class can't be instantiated. It can declare abstract members (a signature with no body) that every concrete subclass must implement:
import 'dart:math';
abstract class Shape {
// Abstract: no body.
double get area;
// Concrete: inherited by all subclasses.
String summary() => '$runtimeType with area ${area.toStringAsFixed(2)}';
}
class Circle extends Shape {
final double radius;
Circle(this.radius);
@override
double get area => pi * radius * radius;
}
class Rect extends Shape {
final double w, h;
Rect(this.w, this.h);
@override
double get area => w * h;
}
void main() {
final shapes = <Shape>[Circle(1), Rect(2, 3), Circle(2.5)];
for (final s in shapes) {
print(s.summary());
}
final total = shapes.fold<double>(0, (sum, s) => sum + s.area);
print('Total: ${total.toStringAsFixed(2)}');
// Shape(); // error: Abstract classes can't be instantiated.
}
Output:
Circle with area 3.14
Rect with area 6.00
Circle with area 19.63
Total: 28.78
If a concrete subclass forgets to implement area, it's a compile-time error.
Type checks and casts
Use is to test whether an object is an instance of a type (including any subtype), and as to cast. Inside an if (x is T) block, Dart promotes a local variable to T automatically:
class Animal {}
class Dog extends Animal {
void bark() => print('woof');
}
class Cat extends Animal {}
void main() {
final Animal a = Dog();
print(a is Animal); // true
print(a is Dog); // true
print(a is Cat); // false
print(a is Object); // true
print(a.runtimeType); // Dog
if (a is Dog) {
a.bark(); // promoted to Dog, no cast needed
}
final Animal c = Cat();
try {
(c as Dog).bark();
} on TypeError catch (e) {
print('cast failed: ${e.runtimeType}');
}
}
Output:
true
true
false
true
Dog
woof
cast failed: _TypeError
Prefer is checks (or a switch with type patterns, see Pattern matching) over as, which throws when the cast is wrong. Also don't compare runtimeType values to check types: a.runtimeType == Animal is false for a Dog, which is rarely what you want.
Implicit interfaces and implements
Every class in Dart also defines an interface: the set of its public instance members. Any other class can promise to provide that interface with implements. Unlike extends, nothing is inherited. You must implement every member yourself, including fields (as getters, plus setters for non-final fields):
class Logger {
final String prefix;
Logger(this.prefix);
void log(String msg) => print('$prefix: $msg');
}
// Implements Logger's interface but shares none of its code.
class SilentLogger implements Logger {
@override
String get prefix => '';
@override
void log(String msg) {}
}
class MemoryLogger implements Logger {
@override
final String prefix = 'mem';
final lines = <String>[];
@override
void log(String msg) => lines.add('$prefix: $msg');
}
void run(Logger logger) {
logger.log('starting');
logger.log('done');
}
void main() {
run(Logger('console'));
run(SilentLogger());
final mem = MemoryLogger();
run(mem);
print(mem.lines);
}
Output:
console: starting
console: done
[mem: starting, mem: done]
This is handy for test doubles: you can fake any class without changing it.
A class can implement any number of interfaces, and can combine that with extends:
abstract interface class Flyer {
void fly();
}
abstract interface class Swimmer {
void swim();
}
class Bird {
void layEgg() => print('laid an egg');
}
class Duck extends Bird implements Flyer, Swimmer {
@override
void fly() => print('duck flies');
@override
void swim() => print('duck swims');
}
void main() {
final d = Duck();
d.layEgg();
d.fly();
d.swim();
print(d is Flyer && d is Swimmer && d is Bird); // true
}
abstract interface class is the Dart 3 way to write a pure interface: it can't be instantiated (abstract) and other libraries can only implement it, not extend it (interface).
Mixins
Single inheritance means a class can't extend two classes. Mixins solve that: a mixin is a bundle of fields and methods that you can add to any class with with:
mixin Walker {
int steps = 0;
void walk(int n) {
steps += n;
print('$runtimeType walked $n steps (total $steps)');
}
}
mixin Swimmer {
void swim() => print('$runtimeType is swimming');
}
class Animal {
final String name;
Animal(this.name);
}
class Duck extends Animal with Walker, Swimmer {
Duck(super.name);
}
class Robot with Walker {}
void main() {
final duck = Duck('Donald');
duck.walk(3);
duck.walk(2);
duck.swim();
Robot().walk(10);
print(duck is Walker); // true
}
Output:
Duck walked 3 steps (total 3)
Duck walked 2 steps (total 5)
Duck is swimming
Robot walked 10 steps (total 10)
true
Mixins can't declare constructors, and a class declared with mixin can't be instantiated or extended.
Restricting a mixin with on
The on clause says a mixin can only be applied to subclasses of a given type. In exchange, the mixin can call that type's members, including through super:
class Account {
int balance = 0;
void deposit(int amount) {
balance += amount;
}
}
mixin Audited on Account {
final history = <String>[];
@override
void deposit(int amount) {
history.add('deposit $amount');
super.deposit(amount); // calls Account.deposit
}
}
class SavingsAccount extends Account with Audited {}
void main() {
final acc = SavingsAccount();
acc.deposit(100);
acc.deposit(50);
print(acc.balance); // 150
print(acc.history); // [deposit 100, deposit 50]
// class Foo with Audited {} // error: Foo doesn't extend Account
}
Mixin order (linearization)
Applying mixins creates a chain of superclasses. class C extends A with M1, M2 produces the hierarchy C -> M2 -> M1 -> A -> Object. The last mixin wins when several define the same member, and super calls walk the chain from right to left:
class Base {
String hello() => 'Base';
}
mixin A on Base {
@override
String hello() => 'A > ${super.hello()}';
}
mixin B on Base {
@override
String hello() => 'B > ${super.hello()}';
}
class AB extends Base with A, B {}
class BA extends Base with B, A {}
void main() {
print(AB().hello());
print(BA().hello());
}
Output:
B > A > Base
A > B > Base
This makes mixins composable: each one can add behavior around the others (logging, caching, validation) and pass the call along with super.
mixin class
A mixin class can be used both as a regular class (instantiated, extended) and as a mixin. It can't have an extends or on clause and can only have a no-argument generative constructor:
mixin class Describable {
String describe() => 'I am a $runtimeType';
}
class Car with Describable {}
class Tree extends Describable {}
void main() {
print(Describable().describe()); // I am a Describable
print(Car().describe()); // I am a Car
print(Tree().describe()); // I am a Tree
}
Class modifiers
By default, any library can extend, implement or instantiate your class. Dart 3 modifiers let library authors restrict that. The restrictions apply only outside the library that declares the class; inside the same library you can do anything.
| Declaration | Construct | Extend | Implement | Mix in | Exhaustive |
|---|---|---|---|---|---|
class |
yes | yes | yes | no | no |
abstract class |
no | yes | yes | no | no |
base class |
yes | yes | no | no | no |
interface class |
yes | no | yes | no | no |
final class |
yes | no | no | no | no |
sealed class |
no | no | no | no | yes |
mixin |
no | no | yes | yes | no |
mixin class |
yes | yes | yes | yes | no |
What each modifier is for:
baseguarantees that every subtype inherits your implementation, so your private members and invariants can't be bypassed by a fake thatimplementsthe class. Subclasses of abaseclass must themselves bebase,finalorsealed.interfacelets others implement your API but not inherit your code, so you're free to change your internal method calls without breaking subclasses.finalcloses the type completely outside its library. You can add members later without breaking anyone.sealeddeclares a closed set of subtypes that must all live in the same library. The class is implicitly abstract.
Modifiers combine: abstract base class, abstract interface class, abstract final class (a common way to declare a namespace of static members that can't be instantiated or subclassed), base mixin, and so on.
Here's what violating them looks like from another library:
// file: lib/vehicles.dart
base class Vehicle {
void drive() => print('driving');
}
interface class Engine {
void start() => print('vroom');
}
final class Vin {
final String code;
Vin(this.code);
}
// file: bin/main.dart
import 'package:demo/vehicles.dart';
base class Truck extends Vehicle {} // OK, subclass is also base
// class Fake implements Vehicle {}
// error: The class 'Vehicle' can't be implemented outside of its library
// because it's a base class.
// class Turbo extends Engine {}
// error: The class 'Engine' can't be extended outside of its library
// because it's an interface class.
class MockEngine implements Engine { // OK
@override
void start() => print('mock start');
}
// class MyVin extends Vin { MyVin() : super('x'); }
// error: The class 'Vin' can't be extended outside of its library
// because it's a final class.
Sealed classes and exhaustive switches
Because the compiler knows every direct subtype of a sealed class, a switch over it is checked for exhaustiveness. No default case is needed, and adding a new subtype turns every incomplete switch into a compile error:
sealed class Result<T> {}
class Ok<T> extends Result<T> {
final T value;
Ok(this.value);
}
class Err<T> extends Result<T> {
final String message;
Err(this.message);
}
Result<int> parse(String s) {
final n = int.tryParse(s);
return n == null ? Err('not a number: $s') : Ok(n);
}
String show(Result<int> r) => switch (r) {
Ok(:final value) => 'ok $value',
Err(:final message) => 'error: $message',
};
void main() {
print(show(parse('42')));
print(show(parse('abc')));
}
Output:
ok 42
error: not a number: abc
What is and isn't inherited
| Member | Inherited by extends? |
|---|---|
| Instance fields, getters, setters, methods, operators | yes |
| Constructors (including factory and named) | no |
| Static fields and methods | no |
Private members (_name) |
yes, but only accessible from code in the declaring library |
Static members belong to the class that declares them. You can't call them through a subclass:
class Parent {
static String greet() => 'hello';
}
class Child extends Parent {}
void main() {
print(Parent.greet()); // hello
// Child.greet(); // error: The method 'greet' isn't defined for the type 'Child'.
}
Privacy in Dart is per library, not per class. A subclass in a different library inherits _secret and the object still carries it, but code in that library can't name it. If it declares its own _secret, that's a separate member that doesn't override the original. See Libraries and visibility.
Requiring overrides to call super
If a subclass override must call the superclass implementation (for example, to release resources), annotate the method with @mustCallSuper from package:meta. The analyzer then warns about overrides that forget:
import 'package:meta/meta.dart';
class Resource {
@mustCallSuper
void dispose() => print('Resource disposed');
}
class FileResource extends Resource {
@override
void dispose() {
print('closing file');
super.dispose(); // remove this line and the analyzer warns
}
}
void main() {
FileResource().dispose();
}
Output:
closing file
Resource disposed
Flutter's State.dispose() and initState() use exactly this annotation.
Inheritance vs composition
Inheritance couples a subclass tightly to its superclass's implementation. Some guidelines:
- Use
extendswhen the subclass really is a specialized version of the parent and should reuse most of its behavior. - Use
implementswhen you only need to satisfy a contract, for example to provide a fake in tests or an alternative implementation. - Use mixins for cross-cutting behavior (logging, equality, serialization helpers) shared by unrelated classes.
- Use a field instead (composition) when you only need some of another class's behavior. Holding a
Loggeris often better than extending one. - Use
sealedfor closed families of types like results, events or AST nodes, so the compiler checks everyswitch. - Use
finalorinterfaceon classes in published packages that weren't designed to be subclassed, so you can evolve them without breaking users.