abstract
- Dart course
- Intermediate
- Lesson 10/116
- 5 min
Learn abstract classes with abstract.
abstract class
An abstract class is one that cannot be instantiated directly. Abstract methods carry only a signature; the body is written in a subclass. It is declared with the abstract class keywords.
Example: abstract class Shape { double area(); }. Here Shape cannot be instantiated: Shape() is a compile error. The area method is left without a body; every subclass must write its own area calculation. Abstract classes are used to define a common contract; subclasses make the contract concrete.
Abstract methods and subclasses
Bodyless methods of an abstract class are written in the subclass with @override. Until the subclass gives bodies it is itself abstract; to become concrete it must implement all abstract methods.
Example: class Circle extends Shape { final double radius; Circle(this.radius); @override double area() => 3.14 * radius * radius; }. Here Circle is a concrete class because it gave a body to area. Since Shape is abstract, no Shape instance exists, but a Circle instance does. The abstract class sets the skeleton for inheritance.
Practice Write the Circle class
Keep the existing abstract class Shape { double area(); } definition. Define a class named Circle that inherits from Shape; add a final double radius field and a Circle(this.radius) constructor. Write the @override double area() => 3.14 * radius * radius; method. In main, create an instance with var c = Circle(2); and call print(c.area()).
Starter code
abstract class Shape {
double area();
}
// Define Circle inheriting from Shape
void main() {
// Create a Circle(2) instance and print c.area()
}Sample solution
abstract class Shape {
double area();
}
class Circle extends Shape {
final double radius;
Circle(this.radius);
@override
double area() => 3.14 * radius * radius;
}
void main() {
var c = Circle(2);
print(c.area());
}Expected output
12.56
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which statement is true?
- An abstract class cannot be instantiated directly
- An abstract class cannot contain final fields Correct answer
- An abstract class may have only one subclass
- All methods of an abstract class must have bodies
Explanation: Abstract classes may contain final fields; only direct instantiation is forbidden.
2 Match the abstract parts
| Term | Meaning |
|---|---|
abstract class |
Class prefix |
double area() |
Abstract method signature |
Circle |
Concrete subclass |
3 Add the abstract keyword
class Shape {
double area();
}____
class Shape {
double area();
}abstract
Explanation: The abstract prefix marks the class as not instantiable.