Summary: in this tutorial, you’ll learn how to use the Dart abstract
keyword to define abstract classes.
Introduction to Dart abstract classes
So far, you have learned how to define classes. These classes are called concrete classes. They’re concrete because you can create new objects out of them.
Besides concrete classes, Dart supports abstract classes. An abstract class is a class declared with the abstract
keyword:
abstract class AbstractClassName
{
}
Code language: Dart (dart)
Unlike a concrete class, you cannot create new objects from an abstract class. The main purpose of the abstract class is to allow other classes to inherit from it.
An abstract class may contain abstract properties and methods. Typically, an abstract class has abstract methods for its child classes to implement.
Abstract methods
Unlike a regular method, an abstract method has only the signature part and doesn’t have an implementation.
For example, the following defines an abstract method in an abstract class:
abstract class AbstractClassName
{
type AbstractMethodName(parameters);
}
Code language: Dart (dart)
When a class inherits from an abstract class, it must implement all the abstract methods that the abstract class has.
Dart abstract classes example
First, define an abstract class called Shape
:
abstract class Shape {
double area();
}
Code language: Dart (dart)
The Shape
class has an abstract method area()
. Since we have many kinds of shapes like circles, squares, etc., each kind of shape should have a different way of calculating its area.
Second, define the Circle
class that inherits from the Shape
class:
class Circle extends Shape {
double radius;
Circle({this.radius = 0});
@override
double area() => 3.14 * radius * radius;
}
Code language: Dart (dart)
The Circle
class provides the detailed implementation of the area()
method. It returns the area of the circle.
Third, define the Square
class that inherits from the Shape
class:
class Square extends Shape {
double length;
Square({this.length = 0});
@override
double area() => length * length;
}
Code language: Dart (dart)
In the square, class the area()
method returns the area of the square.
Finally, create an instance of the Circle
and Square classes and call the area()
method to calculate the area of each:
void main() {
var circle = Circle(radius: 10);
print('The area of the circle is ${circle.area()}');
var square = Square(length: 10);
print('The area of the square is ${square.area()}');
}
Code language: Dart (dart)
Output:
The area of the circle is 314.0
The area of the square is 100.0
Code language: Dart (dart)
Summary
- An abstract class is a class that cannot be instantiated. It’s declared with an
abstract
keyword. - An abstract method only has the signature and doesn’t have the implementation.
- Subclasses of an abstract class must provide an implementation for abstract methods and properties.