Skip to main content
The final modifier restricts the inheritance hierarchy of a class to its defining library, completely closing the class to external extension or implementation while permitting unrestricted instantiation.

Syntax

final class Vehicle {
  // Class members
}

Core Semantics

When a class is marked as final, the Dart type system enforces the following constraints:
  1. Instantiation: The class can be constructed (instantiated) from any library, provided the constructor is accessible (public).
  2. External Inheritance: Classes outside the defining library cannot extend, implement, or use the class as a mixin.
  3. Internal Inheritance: Classes within the same library can extend or implement the final class.

Subtype Constraints

To maintain the closure guarantees of the type system, any class extending or implementing a final class within the same library must also be marked with one of the following modifiers:
  • base
  • final
  • sealed
This requirement prevents the restrictions of the final class from being bypassed by a less restrictive subtype.

Behavior Visualization

File: shapes.dart (Defining Library)
// Declaration
final class Rectangle {
  double width;
  double height;
  
  Rectangle(this.width, this.height);
}

// VALID: Subtyping within the same library is allowed.
// The subclass must be base, final, or sealed.
final class Square extends Rectangle {
  Square(double side) : super(side, side);
}
File: main.dart (External Library)
import 'shapes.dart';

void main() {
  // VALID: Instantiation is allowed everywhere.
  var rect = Rectangle(10, 20);
}

// COMPILER ERROR: Cannot extend a final class from outside its library.
class MyRect extends Rectangle { 
  MyRect(super.width, super.height);
}

// COMPILER ERROR: Cannot implement a final class from outside its library.
class MockRect implements Rectangle {
  @override
  double width = 0;
  @override
  double height = 0;
}

API Surface Guarantee

Because external libraries cannot create new subtypes, the final modifier guarantees that:
  1. Instance Integrity: Any instance of type T (where T is final) originated from the defining library or is a direct instance of T.
  2. Method Resolution: Method overrides cannot be introduced by external code, ensuring that calls to instance methods execute logic defined solely within the library’s scope.
Master Dart with Deep Grasping Methodology!Learn More