Dart Abstract Classes
An abstract class sets a shape that other classes must fill in. It cannot be created on its own.
An abstract class at work
Shape declares the abstract area method and the concrete describe method. Square fills in area and inherits describe.
abstract class Shape {
double area();
void describe() {
print('Area: ${area()}');
}
}
class Square extends Shape {
double side;
Square(this.side);
@override
double area() {
return side * side;
}
}
void main() {
var square = Square(3);
print(square.area());
square.describe();
}Creating an abstract class fails
This program tries to create a Shape directly. The compiler refuses, because an abstract class cannot be instantiated.
abstract class Shape {
double area();
}
void main() {
var shape = Shape();
print(shape.area());
}Implements done completely
Host uses Shape as an interface, so Host re-implements both members. Nothing is inherited, and the program prints.
abstract class Shape {
double area();
void describe() {
print('A shape');
}
}
class Host implements Shape {
@override
double area() {
return 4.0;
}
@override
void describe() {
print('Host shape');
}
}
void main() {
var host = Host();
print(host.area());
host.describe();
}A missing member fails
This Host re-implements area but leaves out describe. The compiler refuses, because implements demands every member.
abstract class Shape {
double area();
void describe() {
print('A shape');
}
}
class Host implements Shape {
@override
double area() {
return 4.0;
}
}
void main() {
var host = Host();
host.describe();
}Example
abstract class Shape {
double area();
void report() {
print('Area is ${area()}');
}
}
class Circle extends Shape {
double radius;
Circle(this.radius);
@override
double area() {
return 3 * radius * radius;
}
}
void main() {
var circle = Circle(2);
circle.report();
}Key points
- The abstract keyword marks a class that cannot be instantiated.
- An abstract method has a signature and no body.
- A concrete method inside an abstract class is shared by every subclass.
- A subclass must write a body for each abstract method it inherits.
- The implements keyword uses a class as an interface instead of a parent.
- With implements, every member must be re-implemented, even the concrete ones.
In this example, Circle fills in the abstract area method. The shared report method comes from Shape and prints the area the subclass computes.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท DartPad
Exercise
What happens when code tries to create an abstract class directly?