On this page10 sections
Lecture 045: Abstract Classes & Interfaces
| Day | Extra Topics |
| Lecture | 045 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
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
implementsto promise a set of methods - Tell
extendsandimplementsapart - 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:
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:
- You can't create an object of an abstract class:
Shape()is an error. - 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.
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:
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
extends | implements | |
|---|---|---|
| Gets the parent's code? | yes | no, you write every member |
| How many? | one class | as many as you like |
| Meaning | "is a kind of" | "can do / promises to do" |
class Duck extends Animal implements Flyer, Swimmer { ... }One parent, many promises.
Code Examples
Example 1: Sending Notifications
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
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
var s = Shape();Error: The class 'Shape' is abstract and can't be instantiated.2. Forgetting an abstract method in a child
class Circle extends Shape {}Error: The non-abstract class 'Circle' is missing implementations for these members:
- Shape.area3. Expecting implements to copy code
class Bird implements Flyable {}Error: The non-abstract class 'Bird' is missing implementations for these members:
- Flyable.flyEven though Flyable.fly has a body, implements copies nothing. Use extends if you want the
code.
4. Writing {} instead of ;
abstract class Shape {
double area() {}
}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
- Can you write
var s = Shape();whenShapeis abstract? - What does an abstract method look like?
- How many classes can a class
extend? How many can itimplement? class Robot implements Walker, andWalkerhas awalk()method with a body. DoesRobotget that body?- Write an abstract class
Vehiclewith an abstract methodint wheels();, and aBikethat extends it.
Practice Answers
- No. Abstract classes can't be instantiated.
- A method signature ending with
;, with no body:double area(); - One with
extends; any number withimplements. - No.
Robotmust write its ownwalk().
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, manyimplements. - Code that depends on an abstract type or interface works with any class that fits it.