TExcelTAD
Home › Dart › Class Modifiers

Class Modifiers

By default, any Dart class can be constructed, extended, implemented and (before Dart 3) mixed in, by any code anywhere. That's flexible, but a library author often wants to say "you may implement this, but not extend it" or "this hierarchy is closed". Dart 3 added class modifiers to express exactly that: abstract, base, interface, final, sealed and mixin.

The key idea: restrictions apply outside the library

Modifiers restrict what other libraries (other files) can do. Inside the same library, you can still extend or implement freely. That's why the examples on this page show the rules in comments — a single runnable file is one library, so every use is allowed there.

Modifier Construct? Extend outside? Implement outside? Typical purpose
(none) ✅ ✅ ✅ Ordinary class
abstract ❌ ✅ ✅ Partial implementation
base ✅ ✅ ❌ Guarantee inherited implementation is used
interface ✅ ❌ ✅ Pure contract; callers can't inherit code
final ✅ ❌ ❌ Closed type, can't be subtyped outside
sealed ❌ ❌ ❌ Closed, known set of subtypes → exhaustive switches
abstract interface ❌ ❌ ✅ Classic "interface"
mixin class ✅ ✅ ✅ Usable as class and mixin

interface

An interface class can be implemented but not extended outside its library. Clients must provide all behaviour; the author can add methods to the class later without breaking subclasses (there aren't any outside):

dart
// lib/storage.dart
interface class Storage {
  String? read(String key) => null;
  void write(String key, String value) {}
}

// bin/app.dart
class MemoryStorage implements Storage { … }  // ✅ allowed
class CachedStorage extends Storage { … }     // ❌ error: can't extend an interface class

base

A base class can be extended but not implemented outside its library. This guarantees that every subtype really inherits the base implementation — for example, that a private invariant-checking method always runs. Subclasses of a base class must themselves be base, final or sealed:

dart
base class Account {
  int _balance = 0;
  void deposit(int amount) {
    if (amount <= 0) throw ArgumentError('amount must be positive');
    _balance += amount;
  }
}

base class SavingsAccount extends Account {} // ✅ extends, and is also base
class Fake implements Account {}             // ❌ outside the library: can't implement a base class

final

A final class can't be extended or implemented outside its library. Use it for value types and implementation details whose behaviour you want to fully control:

dart · try it yourself
final class Money {
  final int cents;
  const Money(this.cents);
  Money operator +(Money other) => Money(cents + other.cents);
  @override
  String toString() => '\${(cents / 100).toStringAsFixed(2)}';
}

void main() {
  const price = Money(1999);
  print(price + const Money(1));
}
$20.00

sealed: closed hierarchies

sealed is the most important modifier for everyday code. A sealed class is abstract, and all its direct subtypes must be declared in the same library. Because the compiler knows the complete list of subtypes, a switch over a sealed type can be checked for exhaustiveness — no default needed, and forgetting a case is a compile error.

dart · try it yourself
sealed class PaymentResult {}

class Success extends PaymentResult {
  final String transactionId;
  Success(this.transactionId);
}

class Declined extends PaymentResult {
  final String reason;
  Declined(this.reason);
}

class NeedsVerification extends PaymentResult {
  final Uri url;
  NeedsVerification(this.url);
}

String message(PaymentResult r) => switch (r) {
      Success(:final transactionId) => 'Paid! Ref $transactionId',
      Declined(:final reason) => 'Declined: $reason',
      NeedsVerification(:final url) => 'Please verify at ${url.host}',
    };

void main() {
  final results = [
    Success('TX-901'),
    Declined('insufficient funds'),
    NeedsVerification(Uri.parse('https://bank.example/3ds')),
  ];
  for (final r in results) {
    print(message(r));
  }
}
Paid! Ref TX-901
Declined: insufficient funds
Please verify at bank.example

Now remove one case and see what the compiler says:

dart · try it yourself
sealed class Shape {}
class Circle extends Shape { final double r; Circle(this.r); }
class Square extends Shape { final double side; Square(this.side); }

double area(Shape s) => switch (s) {
      Circle(:final r) => 3.14 * r * r,
    };

void main() {
  print(area(Square(2)));
}
example.dart:5:33: Error: The type 'Shape' is not exhaustively matched by the switch cases since it doesn't match 'Square()'.
 - 'Shape' is from 'example.dart'.
Try adding a wildcard pattern or cases that match 'Square()'.
double area(Shape s) => switch (s) {
                                ^
Error: AOT compilation failed
Bad state: Generating AOT kernel dill failed!

This is the payoff: when you add a new subtype to a sealed family, the compiler lists every switch that must handle it. Sealed classes plus pattern matching give Dart the algebraic data types found in functional languages. See Switch Expressions & Exhaustiveness.

Combining modifiers

Modifiers combine with abstract and mixin in a few allowed ways:

dart
abstract base class Plugin { void run(); }       // must extend, can't implement
abstract interface class Codec { String encode(Object o); } // pure interface
abstract final class Constants { static const appName = 'Shop'; } // namespace only
mixin class Serializable { String toJson() => '{}'; }

Tip: For your own application code, the most useful modifiers are sealed (for closed families like states, events and results) and abstract interface (for contracts). The others matter most when publishing packages that other people extend.

Test yourself

What does sealed enable that other modifiers don't?

  1. Faster method calls
  2. Exhaustiveness checking in switches over the subtypes
  3. Multiple inheritance
  4. Private constructors

An interface class from another library can be…

  1. Extended only
  2. Implemented only (and constructed)
  3. Neither extended nor implemented
  4. Used as a mixin

Where must the direct subclasses of a sealed class be declared?

  1. Anywhere in the package
  2. In the same library (file) as the sealed class
  3. In a separate part file only
  4. In the test folder