Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 61 ยท Classes and Object-Oriented Dart

Class Modifiers: sealed, final, base

Learn the Dart 3 class modifiers abstract, base, final, interface and sealed, what each one forbids, and how sealed hierarchies give exhaustive switches.

By default, a Dart class is wide open. Anyone can extend it, implement it, or mix it in. That freedom is convenient inside one program, but it is a problem for authors of libraries: every public member becomes a promise that outside code may depend on in ways you never intended. Dart 3 added class modifiers so an author can state precisely how a class may be used.

In this lesson you will meet abstract, base, final, interface and sealed, see what each one allows and forbids outside the declaring library, and use sealed to get exhaustive switch checks. The modifiers are Dart-only features, so the code is read-only; the stand-in at the end models a sealed hierarchy with a TypeScript discriminated union.

The rule of thumb: restrictions apply across libraries

Every modifier restricts what code in other libraries can do. Inside the library that declares the class (usually the same file), nothing is restricted, with the exception of what sealed and the "subtype must keep the restriction" rules require. So the experiments below only show errors when the code is placed in a different file from the declaration.

There are four capabilities to control: construct an instance, extend the class, implement its interface, and mix it in. The modifiers switch these on and off.

Declaration Construct Extend Implement
class A yes yes yes
abstract class A no yes yes
base class A yes yes no
interface class A yes no yes
final class A yes no no
sealed class A no no no

The table lists what is allowed from outside the library. Mixins have their own spelling: mixin M, base mixin M, and mixin class, as explained in Mixins. Plain class can no longer be mixed in.

base: extendable, not implementable

A base class guarantees that every subtype inherits the real implementation. Nobody can bypass your constructor or your private members by writing a class that merely implements it.

DART
// library: lib/connection.dart
base class Connection {
  final String url;
  Connection(this.url);

  void open() => print('opening $url');
}

// another library:
base class SecureConnection extends Connection {   // OK: extends, and keeps "base"
  SecureConnection(super.url);
}

// class FakeConnection implements Connection {}  // error: base classes can't be implemented

A subtype of a base class must itself be marked base, final or sealed. That is the "keep the restriction" rule: the guarantee would be worthless if a subclass could reopen the door by being implementable. Use base for types that hold resources or invariants, such as a database handle, where a fake from outside would break the library's assumptions.

interface: implementable, not extendable

An interface class lets others implement the contract, but not inherit from it, so you remain free to change the internals. This also matches the pure-interface style from Abstract Classes and Implicit Interfaces. Add abstract to forbid construction too: abstract interface class Storage { ... } is the Dart 3 spelling of a classic interface.

final: closed to extension and implementation

A final class can be constructed but not extended or implemented from another library. It is the strictest option that still lets people create instances. It is the right default for classes that are not designed to be subclassed, such as value types and utility objects, and it lets you add new members to the class later without risking breaking an outside subclass or implementation. Core types such as int and String are closed to subclassing in a similar way.

DART
final class Money {
  final int cents;
  const Money(this.cents);

  Money operator +(Money other) => Money(cents + other.cents);
}

sealed: a closed family you can switch over

sealed is the most useful modifier for everyday code. A sealed class is implicitly abstract, and all its direct subtypes must be declared in the same library. The compiler therefore knows the complete list of subtypes, and a switch over a sealed type must cover each of them or the code does not compile.

DART
sealed class Shape {}

class Circle extends Shape {
  final double radius;
  Circle(this.radius);
}

class Rectangle extends Shape {
  final double width, height;
  Rectangle(this.width, this.height);
}

class Triangle extends Shape {
  final double base, height;
  Triangle(this.base, this.height);
}

double area(Shape shape) => switch (shape) {
      Circle(radius: var r) => 3.14159 * r * r,
      Rectangle(width: var w, height: var h) => w * h,
      Triangle(base: var b, height: var h) => b * h / 2,
    };

Remove the Triangle line and the analyzer reports that the switch is not exhaustive. Add a new subtype to the hierarchy later and every switch that needs updating lights up as an error instead of failing at runtime. This is how Dart models "one of these cases" data, the same idea as algebraic data types or enums with payloads.

flowchart TD
    S["sealed class Shape<br/>(implicitly abstract)"] --> C["Circle"]
    S --> R["Rectangle"]
    S --> T["Triangle"]
    X["switch (shape)"] --> Q{"all three<br/>covered?"}
    Q -- yes --> OK["compiles"]
    Q -- no --> ERR["compile-time error"]

Because the subtypes are fixed, the compiler can check that a switch handles every one.

Subtypes of a sealed class can be any kind of class; they may themselves be sealed, final, base, or open. Exhaustiveness descends through nested sealed types. Switch expressions and patterns are covered in switch Statements and Expressions and Patterns and Destructuring.

TypeScript A sealed hierarchy as a discriminated union (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Combining modifiers and choosing one

Some modifiers combine: abstract base class, abstract final class, abstract interface class, base mixin. A few combinations are meaningless and rejected (for example sealed already implies abstract, and final with interface contradict each other). A practical way to choose, for a class that lives in a library other people use:

  • Not designed for subclassing or faking? final class.
  • Designed to be subclassed, but fakes must not skip your code? base class.
  • A contract for others to implement? abstract interface class.
  • A closed set of variants, handled by switch? sealed class.
  • Anything else, or code inside one app where you control all the files? A plain class is fine.

The modifiers matter most when code is split across libraries. In a single-file script they stop nothing, so do not worry about them on day one. Do reach for sealed early, though: exhaustive switches are useful everywhere.

Seeing the restrictions in practice

Real Dart cannot run on this site, so imagine two files. The first declares final class Money. The second contains class Coupon extends Money {}. The analyzer reports an error that the class cannot be extended outside its library, and the same for implements Money. These are compile-time errors, so there is no runtime surprise. The stand-in below shows the nearest TypeScript idea: a private constructor that stops outside subclasses from being created with new.

TypeScript Closing a class to outsiders (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What can another library NOT do with a final class?

    A final class can be constructed from anywhere, but outside its library it can be neither extended nor implemented.
  2. 2. Why does a switch over a sealed type not need a default case?

    All direct subtypes of a sealed class live in the same library, so the compiler can verify exhaustiveness.
  3. 3. Which modifier lets other libraries implement a class but not extend it?

    interface class allows implements only. base is the opposite (extend only), and final allows neither.
  4. 4. What must a subclass of a base class be marked as?

    A subtype of a base class has to keep the restriction, so it must be base, final or sealed. Otherwise the guarantee could be undone.
  5. 5. A sealed class is implicitly what?

    Sealed classes cannot be instantiated directly; they exist so that their subtypes can be enumerated.

Summary

  • Class modifiers control who can construct, extend or implement a class from other libraries; inside the same library nothing is restricted.
  • base allows extending but not implementing, interface the reverse, and final forbids both.
  • abstract forbids construction; abstract interface class is Dart 3's pure contract.
  • sealed is implicitly abstract, keeps all direct subtypes in one library and makes switch exhaustive.
  • Pick the strictest modifier that fits; it leaves you the most freedom to evolve a library.

Next, define a fixed set of named values with Enums and Enhanced Enums.