Unit 4 · The Four Pillars in Depth · 9 min
Abstraction and abstract classes
Abstraction means showing what an object does and hiding how it does it. An abstract class is a partial blueprint that cannot be turned into an object by itself.
Why this matters
It lets you define a common rule ('every shape must have an area') without deciding how each shape calculates it.
Real-life analogy
You press the brake pedal and the car slows down. You do not need to know about brake fluid or discs. That hidden machinery is abstraction.
Syntax
Syntax
abstract class Shape {
abstract double area(); // no body: children must provide it
void describe() { } // normal method is allowed too
}Example
Java
abstract class Shape {
String name;
Shape(String name) {
this.name = name;
}
abstract double area(); // abstract method
void describe() { // concrete method
System.out.println(name + " area = " + area());
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
super("Circle");
this.radius = radius;
}
@Override
double area() { return 3.14 * radius * radius; }
}
class Rectangle extends Shape {
double w, h;
Rectangle(double w, double h) {
super("Rectangle");
this.w = w;
this.h = h;
}
@Override
double area() { return w * h; }
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = { new Circle(2), new Rectangle(4, 5) };
for (Shape s : shapes) {
s.describe();
}
}
}Output
Circle area = 12.56 Rectangle area = 20.0
Step by step
- 1`abstract class Shape` cannot be instantiated: `new Shape()` is a compile error.
- 2`abstract double area();` has no body — every child must supply one.
- 3describe() is a normal method shared by all children.
- 4Each child implements area() in its own way; describe() calls the right one automatically.
Key points
- abstract class = cannot create objects of it
- It can have both abstract and concrete methods, plus constructors and fields
- A child must override every abstract method or itself be abstract
- An abstract class can mix abstract methods with fully implemented methods
Common mistakes
- Writing `new Shape()`
- Forgetting to override an abstract method in the child
- Giving an abstract method a body
Try it yourself
- Create an abstract Employee class with an abstract calculateSalary() method.
- Add a Triangle class to the Shape example.