Skip to content
Tutorials Center
My learning

Topics

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

Abstract Classes and Implicit Interfaces

Understand Dart abstract classes, why every class is also an interface, how implements differs from extends, and what the Dart 3 interface class modifier adds.

Good programs depend on what something can do, not how it does it. A report generator needs "something that can save text", not a specific file class. Dart gives you two tools for that kind of contract: abstract classes, which can hold some shared code, and interfaces, which describe only the shape.

The twist in Dart is that there is no separate interface declaration in the classic sense. Every class implicitly defines an interface, and any other class can implement it. This lesson shows how that works, how it differs from extends, and what the Dart 3 interface modifier changes. Dart code is read-only; the stand-ins use TypeScript's abstract class and interface.

Abstract classes

Put abstract before class and you get a class you cannot instantiate. It may contain abstract members, declared without a body, plus ordinary members with code that subclasses inherit.

DART
abstract class Notifier {
  void send(String message);                 // abstract: no body

  void sendAll(List<String> messages) {      // concrete: shared code
    for (var message in messages) {
      send(message);
    }
  }
}

class ConsoleNotifier extends Notifier {
  @override
  void send(String message) => print('> $message');
}

void main() {
  // var n = Notifier();                     // error: abstract classes can't be instantiated
  Notifier n = ConsoleNotifier();
  n.sendAll(['hello', 'world']);
}

This is the template pattern: the abstract class fixes the overall behavior (sendAll) and leaves one step (send) to subclasses. A non-abstract subclass that forgets to implement send gets a compile-time error. Abstract getters and setters work the same way, and an abstract class can still have constructors, fields and factories, which is how a factory constructor can return different subclasses (see Constructors).

Every class is an interface

When a class is declared, Dart also creates an interface from it: the set of all instance members, public and library-visible. You can implement that interface with the implements keyword, even if the class is not abstract.

DART
class Printer {
  void printLine(String text) => print(text);
  int get width => 80;
}

class FakePrinter implements Printer {
  final List<String> lines = [];

  @override
  void printLine(String text) => lines.add(text);

  @override
  int get width => 20;
}

implements inherits nothing: no code, no fields' initial values, no constructors. You promise to provide every member yourself, and the compiler checks that you did. A FakePrinter can then be passed anywhere a Printer is expected, which is exactly what you want in tests.

flowchart TD
    I["Printer<br/>(class = its own interface)"]
    A["ConsolePrinter<br/>extends Printer<br/>inherits code"]
    B["FakePrinter<br/>implements Printer<br/>inherits nothing"]
    I --> A
    I -.-> B

Solid arrow: extends shares code. Dotted arrow: implements only promises the same members.

TypeScript A fake that implements an interface (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.

extends versus implements

extends implements
How many One class Any number, comma separated
Inherits code Yes No
Constructors Must call the super constructor None to call
Relationship "is a, and reuses" "can be used as, behaves like"
Calling super.method() Yes No

You can combine them: class Duck extends Animal implements Flyer, Swimmer. Because a class can implement many interfaces, this is Dart's way of giving a type several roles without multiple inheritance of code. For sharing code across unrelated classes, use mixins (Mixins).

The obligations of implements are strict. If you implement a class that has a field final String name;, you must provide a name getter, because the field is part of the interface as a getter. Anything with _private names in another library cannot be implemented from outside that library. Note also that if the interface class has a hundred members, you must write a hundred members; abstract classes with few required members are friendlier to implement.

A pure interface in Dart

Dart programmers write a pure interface as an abstract class with only abstract members:

DART
abstract class Storage {
  Future<String?> read(String key);
  Future<void> write(String key, String value);
}

class MemoryStorage implements Storage {
  final Map<String, String> _data = {};

  @override
  Future<String?> read(String key) async => _data[key];

  @override
  Future<void> write(String key, String value) async => _data[key] = value;
}

Code that depends on Storage can run against MemoryStorage in tests and a file-based version in production. The Future parts are explained in Futures and async/await.

The interface class modifier (Dart 3)

Because any class can be implemented, the author of a library cannot stop outsiders from implementing it, and later changes to the class may break them. Dart 3 adds class modifiers so authors can say what is allowed. One of them is interface:

DART
interface class Clock {
  DateTime now() => DateTime.now();
}

An interface class can be implemented (and instantiated, because it is not abstract) but not extended outside its own library. Combine it with abstract as abstract interface class Storage { ... } to make a pure contract that others can only implement, never instantiate and never inherit from. The full set of modifiers is covered in Class Modifiers: sealed, final, base.

Without a modifier a class is open in both directions, which is the behavior of everything you wrote earlier in this chapter. Modifiers are optional, but they are valuable in libraries you share.

TypeScript Template method with an abstract class (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 you NOT do with an abstract class?

    An abstract class cannot be instantiated directly. It can be extended or implemented, and it may contain concrete members.
  2. 2. What does class FakePrinter implements Printer inherit from Printer?

    implements copies the shape, not the code. The compiler requires you to provide every member of the interface.
  3. 3. Which class declaration is valid?

    A class can extend only one class, but it can implement many interfaces separated by commas.
  4. 4. What does the Dart 3 interface class modifier forbid outside its library?

    An interface class can be implemented and instantiated, but other libraries cannot extend it.
  5. 5. Why is implementing an interface useful in tests?

    Because the fake has the same members as the real class, code that depends on the interface accepts either one.

Summary

  • An abstract class cannot be instantiated; it can mix abstract members with shared concrete code.
  • Every class defines an implicit interface; implements promises the same members without inheriting any code.
  • A class extends one class but can implement many interfaces.
  • A pure contract is an abstract class with only abstract members; fakes and alternative implementations plug into it.
  • Dart 3 modifiers such as interface class let library authors restrict how a class may be used.

Next, share behavior across unrelated classes with Mixins.