On this page10 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Abstract Classes
  4. 2. Interfaces With implements
  5. 3. extends vs implements
  6. Code Examples
  7. Common Beginner Mistakes
  8. Practice Questions
  9. Practice Answers
  10. Key Takeaways

Lecture 045: Abstract Classes & Interfaces

DayExtra Topics
Lecture045 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

Some classes are ideas, not things. "A shape" is an idea; you can only draw a real square or circle. An abstract class describes the idea and forces every real class to fill in the details. An interface is a promise: "any class that implements me has these methods".

Contents

Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways


Prerequisites

Lectures 042–044: inheritance, overriding and polymorphism.


Learning Objectives

  • Create an abstract class with abstract
  • Write abstract methods (no body) that children must override
  • Use implements to promise a set of methods
  • Tell extends and implements apart
  • Implement more than one interface

1. Abstract Classes

Put abstract before class. An abstract class can have abstract methods, which end with ; instead of a body:

dart
abstract class Shape {
  double area();          // no body: every shape must provide one

  void describe() {       // a normal method, shared by all shapes
    print('$runtimeType with area ${area().toStringAsFixed(2)}');
  }
}

class Square extends Shape {
  final double side;
  Square(this.side);

  @override
  double area() => side * side;
}

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

  @override
  double area() => 3.14159 * radius * radius;
}

void main() {
  Square(3).describe();   // Square with area 9.00
  Circle(1).describe();   // Circle with area 3.14
}

Two rules:

  1. You can't create an object of an abstract class: Shape() is an error.
  2. Every normal child must override all abstract methods, or Dart won't compile it.

2. Interfaces With implements

implements means "I promise to have every method and field of that class, written by me". Nothing is inherited; you write it all yourself.

dart
abstract interface class Printable {
  void printMe();
}

class Invoice implements Printable {
  final int number;
  Invoice(this.number);

  @override
  void printMe() => print('Invoice #$number');
}

abstract interface class (Dart 3) says the class exists only to be implemented. In Dart, any class can be used as an interface:

dart
class Flyable {
  void fly() => print('Flying');
}

class Plane implements Flyable {
  @override
  void fly() => print('The plane takes off');   // must be written again
}

3. extends vs implements

extendsimplements
Gets the parent's code?yesno, you write every member
How many?one classas many as you like
Meaning"is a kind of""can do / promises to do"
dart
class Duck extends Animal implements Flyer, Swimmer { ... }

One parent, many promises.


Code Examples

Example 1: Sending Notifications

dart
abstract interface class Notifier {
  void send(String message);
}

class EmailNotifier implements Notifier {
  final String address;
  EmailNotifier(this.address);

  @override
  void send(String message) => print('Email to $address: $message');
}

class SmsNotifier implements Notifier {
  final String phone;
  SmsNotifier(this.phone);

  @override
  void send(String message) => print('SMS to $phone: $message');
}

class PushNotifier implements Notifier {
  @override
  void send(String message) => print('Push notification: $message');
}

void notifyAll(List<Notifier> channels, String message) {
  for (var c in channels) {
    c.send(message);
  }
}

void main() {
  notifyAll([
    EmailNotifier('sara@mail.com'),
    SmsNotifier('0300-1234567'),
    PushNotifier(),
  ], 'Your order has shipped!');
}

Output

code
Email to sara@mail.com: Your order has shipped!
SMS to 0300-1234567: Your order has shipped!
Push notification: Your order has shipped!

notifyAll only depends on the Notifier promise. A new WhatsAppNotifier would work without changing it.


Common Beginner Mistakes

1. Creating an object of an abstract class

dart
var s = Shape();
code
Error: The class 'Shape' is abstract and can't be instantiated.

2. Forgetting an abstract method in a child

dart
class Circle extends Shape {}
code
Error: The non-abstract class 'Circle' is missing implementations for these members:
 - Shape.area

3. Expecting implements to copy code

dart
class Bird implements Flyable {}
code
Error: The non-abstract class 'Bird' is missing implementations for these members:
 - Flyable.fly

Even though Flyable.fly has a body, implements copies nothing. Use extends if you want the code.

4. Writing {} instead of ;

dart
abstract class Shape {
  double area() {}
}
code
Error: A non-null value must be returned since the return type 'double' doesn't allow null.

{} makes it a normal method with an empty body. An abstract method ends with ;.


Practice Questions

  1. Can you write var s = Shape(); when Shape is abstract?
  2. What does an abstract method look like?
  3. How many classes can a class extend? How many can it implement?
  4. class Robot implements Walker, and Walker has a walk() method with a body. Does Robot get that body?
  5. Write an abstract class Vehicle with an abstract method int wheels();, and a Bike that extends it.

Practice Answers

  1. No. Abstract classes can't be instantiated.
  2. A method signature ending with ;, with no body: double area();
  3. One with extends; any number with implements.
  4. No. Robot must write its own walk().
dart
abstract class Vehicle {
  int wheels();
}

class Bike extends Vehicle {
  @override
  int wheels() => 2;
}

Key Takeaways

  • abstract class = an idea that can't be created directly.
  • Abstract methods (double area();) must be overridden by every normal child.
  • implements = a promise to provide all members; no code is inherited.
  • One extends, many implements.
  • Code that depends on an abstract type or interface works with any class that fits it.