DartIntermediate 2 min read

Dart class modifiers: base, interface, final and sealed

Choose an explicit extension contract for a library rather than exposing accidental inheritance.

On this page

A published model or service is a contract for other libraries. Class modifiers communicate which kinds of reuse are supported. Make that decision before external packages depend on subclassing implementation details.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
abstract interface class Repository<T> {
  T? find(int id);
}

final class MemoryRepository<T> implements Repository<T> {
  MemoryRepository(Map<int, T> items) : _items = Map.of(items);
  final Map<int, T> _items;
  @override
  T? find(int id) => _items[id];
}

void main() {
  final Repository<String> repository = MemoryRepository({7: 'Invoice'});
  print(repository.find(7));
}

Follow the data and control flow

The abstract interface invites implementations while promising no concrete implementation reuse. The final class supplies one implementation and restricts subclassing/implementation from other libraries. Its map is copied, so later changes to the caller’s map do not replace the stored entries.

base preserves implementation inheritance across library boundaries, while sealed defines a closed direct-subtype family useful for exhaustive switches. These restrictions are library-based; one-file examples cannot demonstrate every external-library diagnostic. Use separate libraries when testing your package contract.

A mistake to avoid

Do not add modifiers to every class by habit. Restricting an existing public class can be a breaking package change. Likewise, a private field or a final class is not an access-control system for user data.

Practice and verification

Move the interface and implementation into a library and try subclassing the final class from a second library. Read the diagnostic. Compare that result with a deliberately extensible base class and document the intended consumer behavior.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.