Sub topic 12
Abstract classes and implicit interfaces
This chapter assumes you can write a Dart class with fields, methods, and constructors, and that you know extends and super from the previous chapter. Here you will learn how to declare a class that cannot be instantiated and exists only to define a contract. You will also learn how any class can serve as an interface.
Abstract classes
An abstract class is a class marked with the abstract modifier. You cannot create an instance of it directly. It exists so that other classes can extend or implement it.
An abstract class can contain two kinds of members:
- Abstract members have a signature but no body. Subclasses must supply the body.
- Concrete members have a body. Subclasses inherit them.
abstract class Shape {
double get area;
String get name;
String describe() => '$name with area ${area.toStringAsFixed(2)}';
}
class Circle extends Shape {
final double radius;
Circle(this.radius);
@override
String get name => 'Circle';
@override
double get area => 3.14159 * radius * radius;
}
class Rectangle extends Shape {
final double width;
final double height;
Rectangle(this.width, this.height);
@override
String get name => 'Rectangle';
@override
double get area => width * height;
}
void main() {
final shapes = <Shape>[Circle(1), Rectangle(2, 3)];
for (final shape in shapes) {
print(shape.describe());
}
}This prints Circle with area 3.14 and Rectangle with area 6.00.
describe is written once, in terms of members that the subclasses provide. This pattern is often called a template method. Calling Shape() is a compile-time error, because Shape is abstract.
Rules for abstract members
- A method without a body (
double perimeter();) is abstract. A getter without a body (double get area;) is also abstract. - A non-abstract class must implement every abstract member it inherits. If it doesn't, the analyzer reports an error.
- An abstract class may leave members unimplemented, and so may its abstract subclasses.
- A field that you want subclasses to define can be declared with the
abstractkeyword, for exampleabstract int size;. It behaves like an abstract getter and setter pair.
Abstract classes and constructors
An abstract class can declare constructors. Subclasses call them through super, just as with any other superclass. An abstract class can also declare factory constructors that return instances of concrete subclasses. Callers then depend only on the abstract type.
Dart does not add a default constructor to a class that declares any constructor. If an abstract class declares only factory constructors, other classes can implement it but cannot extend it. The example below relies on that.
abstract class Notifier {
factory Notifier.forChannel(String channel) => switch (channel) {
'email' => EmailNotifier(),
'sms' => SmsNotifier(),
_ => throw ArgumentError.value(channel, 'channel', 'unknown channel'),
};
void send(String message);
}
class EmailNotifier implements Notifier {
@override
void send(String message) => print('Email: $message');
}
class SmsNotifier implements Notifier {
@override
void send(String message) => print('SMS: $message');
}
void main() {
final notifier = Notifier.forChannel('sms');
notifier.send('Build finished');
}Implicit interfaces
Dart has no interface declaration that every program must use. Instead, every class implicitly defines an interface. The interface consists of all the instance members of the class: methods, getters, setters, and fields (each field counts as a getter, plus a setter if it is not final). Any other class can promise to provide that set of members by using implements.
class Logger {
final String prefix;
Logger(this.prefix);
void log(String message) => print('[$prefix] $message');
}
class SilentLogger implements Logger {
@override
String get prefix => 'silent';
@override
void log(String message) {}
}
void run(Logger logger) => logger.log('started');
void main() {
run(Logger('app'));
run(SilentLogger());
}SilentLogger is not a subclass of Logger, yet it can be passed anywhere a Logger is expected. Two details matter here:
Loggerhas afinalfield namedprefix.SilentLoggersatisfies that part of the interface with a getter.SilentLoggermust override every instance member ofLogger. If it leaves one out, the analyzer reports an error.
Implementing several interfaces
A class can extend only one class, but it can implement as many interfaces as it needs. List them after implements, separated by commas.
abstract interface class Readable {
String read();
}
abstract interface class Writable {
void write(String data);
}
class MemoryFile implements Readable, Writable {
String _content = '';
@override
String read() => _content;
@override
void write(String data) {
_content = data;
}
}
void main() {
final file = MemoryFile();
file.write('hello');
print(file.read());
}When a class uses several clauses, they appear in a fixed order: extends, then with, then implements. For example, class Duck extends Animal with Swimmer implements Pet.
What you cannot implement
You cannot implement the core types int, double, num, String, bool, or Null. The analyzer rejects it, because the runtime depends on their exact representation. The Dart 3 modifiers described in the later chapter on class modifiers also restrict who can implement a class from another library.
extends versus implements
| Row | `extends` | `implements` |
|---|---|---|
| How many per class | One | Any number |
| Inherits method bodies | Yes | No |
| Inherits field storage | Yes | No, you declare your own |
| Inherits constructors | No, but the subclass can call them through `super` | No |
| Must override | Only abstract members | Every instance member |
| `super.member()` allowed | Yes | No |
| `is` check against the type | `true` | `true` |
The last row is what makes interfaces useful. A SilentLogger passes logger is Logger, so code that accepts a Logger works with it unchanged.
Choosing between an abstract class and an interface class
Any class can be implemented, so you do not need an abstract class just to create an interface. You write one when you want one or more of these things:
- To prevent anyone from creating a bare instance of the type.
- To share concrete code with subclasses while leaving some members open.
- To expose a factory constructor that hides which subclass is returned.
Since Dart 3, the abstract interface class form in the Readable example states the intent explicitly. The interface modifier means that code outside the declaring library can implement the class but cannot extend it. The abstract modifier means it cannot be instantiated.
Common errors
- Instantiating an abstract class.
Shape()fails to compile. Instantiate a concrete subclass, or call a factory constructor that returns one. - Forgetting a member when implementing. The error names the missing member. Remember that every non-private field of the interface counts as a getter, and as a setter if the field is not
final. - Calling
superafterimplements. An implementing class has no superclass behavior. Copy the logic, or extend the class instead. - Expecting constructors to carry over.
implementsandextendsnever inherit constructors. Declare the ones you need. - Declaring an abstract method in a concrete class. A class that contains a body-less method must itself be marked
abstract.
Exercise
You have class Counter { int value = 0; void increment() => value++; }. Write a class FixedCounter that implements Counter and always keeps value at 10, ignoring increment. Why must it declare both a getter and a setter for value?
Show answer
Example: class FixedCounter implements Counter { @override int get value => 10; @override set value(int v) {} @override void increment() {} }. The value field in Counter is not final, so its interface contains both a getter and a setter. An implementing class must provide both, and the compiler reports an error if the setter is missing. You could also declare int value = 10; as a field, which supplies both members at once.
Exercise
A class Report extends Document and wants to be usable wherever Printable and Exportable are expected. Both are abstract interface classes. Write the class header.
Show answer
class Report extends Document implements Printable, Exportable. The extends clause comes first and the implements clause lists each interface, separated by commas. Report must then override every member of Printable and Exportable, and inherits Document's concrete members.