Sub topic 9
Inheritance, abstract classes, and mixins
This chapter covers how Dart classes share behavior: single inheritance with extends, abstract classes, implicit interfaces with implements, and mixins. It assumes you can write a Dart class with fields, constructors, and methods, and that you know null safety basics. You should also know what final fields and this.field constructor parameters do.
Four ways to reuse behavior
Dart gives you four tools. Each answers a different question.
| Tool | Keyword | What the class gets | How many allowed |
|---|---|---|---|
| Inheritance | `extends` | Fields, methods, and constructor chaining of one superclass | One |
| Interface | `implements` | Only the member signatures. You write all the bodies. | Many |
| Mixin | `with` | Fields and method bodies, with no constructor | Many |
| Abstract class | `abstract` | A base type that cannot be instantiated | Used with the above |
Extending a class
A subclass inherits every instance member of its superclass. Use @override when you replace one. The analyzer then reports an error if the member you meant to override doesn't exist. Use super.member to call the superclass version.
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()} (dog, $breed)';
}
void main() {
final d = Dog('Rex', 'Collie');
print(d.describe());
}This prints Animal Rex (dog, Collie).
Dog(super.name, this.breed) uses a super parameter. It forwards the first argument to Animal's constructor. It is shorthand for the older form:
Dog(String name, this.breed) : super(name);If you use an initializer list, the super(...) call must come last in it.
Constructors are not inherited
A subclass does not get its superclass's constructors. If you write no constructor, Dart gives you an implicit one that calls the superclass's unnamed, zero-argument constructor. That fails to compile when the superclass has no such constructor. This is the most common inheritance error:
class Animal {
final String name;
Animal(this.name);
}
// Error: the implicit constructor calls super(), but Animal() doesn't exist.
class Cat extends Animal {}The fix is to declare Cat(super.name);.
Dart has single inheritance. A class has exactly one superclass, and Object is the root when you write no extends.
Override rules
An override must be compatible with the member it replaces:
- The return type must be the same type or a subtype.
- Parameter types must be the same type or a supertype. You may add optional parameters, but not required ones.
- A getter can be overridden by a getter, and a field can override a getter or setter.
If you want to narrow a parameter type anyway, mark it covariant. Dart then checks the type at runtime instead of at compile time, so use it sparingly.
Abstract classes
An abstract class cannot be instantiated. It exists to define a type and to share code. It can declare abstract members, which have no body, and concrete members. It can also have fields and constructors, which subclasses call through super.
abstract class Animal {
final String name;
Animal(this.name);
String sound(); // abstract: no body
String speak() => '$name says ${sound()}';
}
class Dog extends Animal {
Dog(super.name);
@override
String sound() => 'Woof';
}
void main() {
// Animal('x'); // Error: abstract classes can't be instantiated.
print(Dog('Rex').speak());
}A concrete subclass must implement every abstract member it inherits, or the compiler reports an error. A subclass that is itself abstract may leave some unimplemented.
speak() is a template method. The abstract class fixes the algorithm, and subclasses fill in one step.
Implicit interfaces
Every Dart class also defines an interface made of its public members. You can implement a class even if it was never meant as an interface:
abstract class Logger {
void log(String message);
}
class ConsoleLogger implements Logger {
@override
void log(String message) => print('[console] $message');
}
void main() {
Logger logger = ConsoleLogger();
logger.log('started');
}implements copies no code. If the interface class has fields, you must provide matching getters, and setters for non-final fields. You also don't call a superclass constructor. A class can implement several interfaces: class A implements B, C.
Choose between extends and implements like this. Use extends when you want the inherited code and an "is-a" relationship with shared state. Use implements when you only need to satisfy a contract, for example when you write a test fake for a service.
Mixins
A mixin packages members that several unrelated classes can reuse. It declares methods and fields, but no generative constructor, and it cannot use extends. You apply it with with.
mixin Walker {
void walk() => print('$runtimeType walks');
}
abstract class Animal {
final String name;
Animal(this.name);
String sound();
}
class Dog extends Animal with Walker {
Dog(super.name);
@override
String sound() => 'Woof';
}
void main() {
final dog = Dog('Rex');
print('${dog.name}: ${dog.sound()}');
dog.walk();
}The output is Rex: Woof, then Dog walks.
Dog still has one superclass, Animal. Mixins are layered on top of it, so they don't create multiple inheritance of state with constructors.
Restricting a mixin with `on`
A mixin can declare that it only works on subtypes of a given class. With on, the mixin can call super members of that class:
class Animal {
final String name;
Animal(this.name);
String sound() => '...';
}
class Dog extends Animal {
Dog(super.name);
@override
String sound() => 'Woof';
}
mixin Loud on Animal {
@override
String sound() => '${super.sound().toUpperCase()}!';
}
class LoudDog extends Dog with Loud {
LoudDog(super.name);
}
void main() {
print(LoudDog('Rex').sound());
}This prints WOOF!. The call super.sound() inside Loud reaches Dog.sound(), because the mixin sits between LoudDog and Dog in the class chain. Applying Loud to a class that doesn't extend Animal is a compile error.
Order matters
When several mixins define the same member, the last one listed wins:
mixin A {
String who() => 'A';
}
mixin B {
String who() => 'B';
}
class C with A, B {}
void main() {
print(C().who());
}This prints B. Dart builds a chain of classes from left to right, with each mixin layered over the previous one. A mixin's super calls go to whatever is to its left in that chain. A member declared in the class body itself beats all of its mixins.
Class modifiers in Dart 3
Dart 3 added modifiers that restrict how a class can be used outside its own library (usually one file). They matter mostly for package authors.
| Modifier | Outside its library you can... | Notes |
|---|---|---|
| none | extend, implement, mix in (plain classes only) | The default |
| `abstract` | extend and implement, but not instantiate | Can have abstract members |
| `base` | extend, but not implement | Subtypes must be `base`, `final`, or `sealed` |
| `interface` | implement, but not extend | Protects the class's internals from subclasses |
| `final` | neither extend nor implement | Instantiation is still allowed |
| `sealed` | neither; it is implicitly abstract | Enables exhaustive `switch` |
mixin class declares something usable both as a class and as a mixin. A plain mixin cannot be instantiated or extended, and a plain class cannot be used with with in Dart 3. Sealed classes pair with pattern matching, which a later chapter covers.
Common errors
- Implicit super constructor missing. Add an explicit constructor that calls
super(...), or use super parameters. - Missing implementation. A concrete class that doesn't implement every abstract member fails to compile. The error message names the missing members.
- Instantiating an abstract class. Return a concrete subclass instead. A
factoryconstructor on the abstract class can do this. - Mixin with a constructor. Mixins can't declare one. Move the setup into a method, or use
mixin classwithout parameters. implementswithout a body.implementsinherits nothing, so each member needs a body, including getters for fields.- Wrong mixin order. If a result is unexpected, check which mixin comes last.
Exercise
This code fails to compile. Why, and what is the smallest change that fixes it? class Animal { final String name; Animal(this.name); } class Cat extends Animal {}
Show answer
Cat has no constructor, so Dart creates an implicit one that calls Animal(). Animal has only a one-argument constructor, so that call is invalid. Add a constructor that forwards the argument: Cat(super.name);
Exercise
Given mixin A { String who() => 'A'; }, mixin B { String who() => 'B'; }, and class D with B, A {}, what does D().who() return? What if D also declares its own who() returning 'D'?
Show answer
It returns 'A', because the last mixin listed is applied last and wins. If D declares its own who(), it returns 'D', because a member in the class body overrides all of its mixins.