Sub topic 15
Class modifiers: abstract, base, interface, final, sealed, and mixin class
This chapter assumes you can write a Dart class with constructors, use extends, implements, and with, and read a switch expression. Dart 3 adds keywords in front of class that restrict how code in other libraries may use your class. They turn design intent, such as "this type is a closed set" or "nobody should subclass this", into compile-time errors.
What a modifier controls
A plain class in Dart 3 can be instantiated, extended, and implemented by anyone. It cannot be mixed in unless it is declared mixin class. Modifiers narrow the other capabilities.
A library is usually one file, unless you use part files. Every restriction in this chapter applies only to code outside the declaring library. Inside the same library, you can extend, implement, and construct freely, except where a modifier makes the class abstract.
| Declaration | Instantiate | Extend | Implement | Mix in |
|---|---|---|---|---|
| `class` | yes | yes | yes | no |
| `abstract class` | no | yes | yes | no |
| `base class` | yes | yes | no | no |
| `interface class` | yes | no | yes | no |
| `final class` | yes | no | no | no |
| `sealed class` | no | no | no | no |
| `mixin class` | yes | yes | yes | yes |
The table describes use from another library. A sealed class is also implicitly abstract.
abstract
abstract means you cannot create an instance directly. The class may declare members without bodies, and subclasses must supply them. You met this in the chapter on abstract classes. As a modifier it combines with others:
abstract base classabstract interface classabstract final class
The second form is the pure contract from the spine example, abstract interface class Shape. Outsiders can implement it but cannot extend it, and nobody can construct it.
interface
An interface class can be implemented outside its library but not extended there. Every class in Dart already has an implicit interface. This modifier removes inheritance from the allowed uses.
// file: lib/shape.dart
abstract interface class Shape {
double get area;
}// file: bin/main.dart
import '../lib/shape.dart';
class Square implements Shape {
final double side;
Square(this.side);
@override
double get area => side * side;
}
// class Wide extends Shape {} // Error: 'Shape' can't be extended outside its library.
void main() => print(Square(3).area);The benefit is that your methods never call each other through a hidden inheritance chain you didn't plan for. An implementer must override every member, so none of your internal call patterns leak into subclasses.
base
A base class can be extended but not implemented outside its library. This guarantees that every instance of the type was built through one of your constructors, so your field initializers and constructor logic always ran.
// file: lib/account.dart
base class Account {
final String id;
int balance = 0;
Account(this.id);
}// file: bin/main.dart
import '../lib/account.dart';
base class Savings extends Account {
Savings(super.id);
}
// class Fake implements Account {} // Error: 'Account' can't be implemented outside its library.
// class Checking extends Account {} // Error: must be 'base', 'final', or 'sealed'.
void main() => print(Savings('s-1').balance);A subtype of a base class must itself be marked base, final, or sealed. The rule applies to the whole hierarchy, so an outside class cannot reintroduce implements further down.
Base also applies to mixins. A base mixin can be applied with with, but no class can implement it outside its library.
final
final class combines both restrictions. Outside the library the class can only be instantiated. Use it when the class is a closed implementation detail, or when you want freedom to add members later. Adding a method to an interface type breaks outside implementers. Adding one to a final class cannot, because no outside class can implement or extend it.
Subtypes of a final class inside the same library are allowed. They need no modifier of their own, though their own subtypes must be base, final, or sealed.
final class Config {
final Map<String, String> values;
const Config(this.values);
}Many core Dart types are closed this way: int, String, and List can't be extended by your code.
sealed
sealed declares a closed set of direct subtypes, all in the same library. The compiler knows every subtype, so a switch over the sealed type must be exhaustive. A sealed class is implicitly abstract and cannot be extended or implemented outside its library.
sealed class Result {}
final class Ok extends Result {
final int value;
Ok(this.value);
}
final class Err extends Result {
final String message;
Err(this.message);
}
String show(Result r) => switch (r) {
Ok(:final value) => 'ok $value',
Err(:final message) => 'error $message',
};
void main() {
print(show(Ok(3)));
print(show(Err('boom')));
}If you add a Pending subclass later, every switch over Result stops compiling until it handles the new case. That is the main reason to choose sealed.
Exhaustiveness covers subtypes of subtypes too. If Ok were a plain class that someone subclassed in the same library, the switch would still need to cover those subclasses, or cover Ok itself.
mixin class
mixin class declares one type that works both as a mixin and as a regular class. It is the only way to use a class in a with clause in Dart 3.
mixin class Counter {
int _count = 0;
int increment() => ++_count;
}
class Clicker with Counter {}
class Tally extends Counter {}
void main() {
final c = Clicker();
c.increment();
print(c.increment()); // 2
print(Tally().increment()); // 1
}Because the declaration works as a mixin, it has the mixin's limits:
- It cannot have an
extendsclause (other than the implicitObject). - It cannot have a
withclause. - It cannot have an
onclause. - It cannot declare generative constructors with parameters. A mixin has no constructor arguments to pass along.
If you need on, declare a plain mixin instead. The only modifiers allowed on a mixin class are abstract and base, so base mixin class is legal. interface mixin class, final mixin class, and sealed mixin class are not.
Which combinations are legal
Some modifier pairs contradict each other, and the analyzer rejects them. A few combinations are redundant.
sealedalready implies abstract and closed, so do not addabstract,base,final, orinterface.finalcannot combine withbaseorinterface, because it already includes both.baseandinterfacecannot combine, because each removes a capability the other keeps.abstractcan combine withbase,interface,final, ormixin class.
Choosing in practice
Start with the most restrictive modifier that fits and relax it only when a real need appears. Loosening later is a compatible change. Tightening later breaks existing users.
- Use
sealedfor a fixed set of variants you will switch over. - Use
finalfor concrete classes with no planned extension. - Use
basewhen your constructors enforce invariants that every instance must satisfy. - Use
interfaceorabstract interfacefor contracts that others implement. - Use
mixin classonly when the same behavior must work both ways.
Libraries you publish are where modifiers matter most. Within an application, where you own all the code, they mostly document intent.
Exercise
You publish a package with base class Repository. A user writes class FakeRepository implements Repository { ... } in their own package for tests. Does it compile, and what are two ways to let them write test doubles?
Show answer
It does not compile, because a base class cannot be implemented outside its library. You can change Repository to interface class (or abstract interface class) so outsiders may implement it, or provide a separate class in your library, such as a final class InMemoryRepository, that users can instantiate or wrap in tests.
Exercise
A sealed class Shape has final class Circle and final class Rect in the same library. You write switch (shape) { Circle() => 1 } and nothing else. What happens, and what happens when you add final class Triangle extends Shape and keep a switch that covers Circle and Rect?
Show answer
The first switch fails to compile because it does not cover Rect. After adding Triangle, the switch that covers only Circle and Rect also fails to compile, because it no longer covers every subtype. Add a Triangle case or a default case.
Exercise
Why can't you write mixin class Loud on Animal?
Show answer
A mixin class can also be used as an ordinary class, and an ordinary class has no required superclass to satisfy an on constraint. To restrict the applicable superclasses, declare it as a plain mixin Loud on Animal.