What are Abstract Classes?
An abstract class is a class that cannot be instantiated directly — you cannot create an object of an abstract class. It serves as a template for subclasses, defining which methods they MUST implement.
Syntax
abstract class Animal {
String name;
Animal(this.name);
// Abstract method — no body, must be implemented by subclasses
void speak();
// Concrete method — has a body, inherited as-is
void breathe() => print('$name is breathing.');
}
Abstract Methods
Abstract methods have no implementation in the abstract class. Every non-abstract subclass MUST implement them:
class Dog extends Animal {
Dog(String name) : super(name);
@override
void speak() => print('$name barks!'); // must implement
}
class Cat extends Animal {
Cat(String name) : super(name);
@override
void speak() => print('$name meows!');
}
// var a = Animal('X'); ← ERROR: abstract class cannot be instantiated
Example
abstract class Shape {
String color;
Shape(this.color);
// Abstract methods — must implement
double area();
double perimeter();
// Concrete method — shared logic
void describe() {
print('$color shape: area=$${area().toStringAsFixed(2)}, '
'perimeter=$${perimeter().toStringAsFixed(2)}');
}
}
class Circle extends Shape {
double radius;
Circle(String color, this.radius) : super(color);
@override double area() => 3.14159 * radius * radius;
@override double perimeter() => 2 * 3.14159 * radius;
}
class Rectangle extends Shape {
double w, h;
Rectangle(String color, this.w, this.h) : super(color);
@override double area() => w * h;
@override double perimeter() => 2 * (w + h);
}
void main() {
List<Shape> shapes = [
Circle('red', 7),
Rectangle('blue', 4, 9),
];
for (var s in shapes) s.describe();
}
Output:red shape: area=153.94, perimeter=43.98
blue shape: area=36.00, perimeter=26.00
🧠 Quiz
1. Can you create an object of an abstract class?
- A) Yes
- B) No ✅
- C) Only with a factory constructor
- D) Only if it has no abstract methods
2. Must subclasses implement all abstract methods?
- A) No, they are optional
- B) Yes, or they must also be abstract ✅
- C) Only if they override them
- D) Only public abstract methods
Summary
Abstract classes define a contract — methods that all subclasses must implement. They cannot be instantiated directly. Use abstract class when you want to enforce a common interface while sharing some concrete implementation. Subclasses use extends to inherit and must implement all abstract methods.