ProLesson 4.7Intermediate3 min readUpdated 30 October 2026
Abstract classes vs interfaces
Define what objects must do without saying how. Learn abstract classes, interfaces, default methods, and how to choose between them.
Abstraction means showing what something does and hiding how. You press "Pay" in an app without knowing which bank API it calls. Java gives you two tools for this: abstract classes and interfaces.
01Abstract classes
An abstract class is a partly built class. It can have normal fields and methods, plus abstract methods with no body that subclasses must implement. You can't create an object of an abstract class directly.
AbstractDemo.java
abstract class Shape {
private final String name;
Shape(String name) {
this.name = name;
}
abstract double area(); // no body: every shape must provide it
String describe() { // shared code
return name + " with area " + String.format("%.2f", area());
}
}
class Circle extends Shape {
private final double r;
Circle(double r) { super("Circle"); this.r = r; }
@Override double area() { return Math.PI * r * r; }
}
class Rectangle extends Shape {
private final double w, h;
Rectangle(double w, double h) { super("Rectangle"); this.w = w; this.h = h; }
@Override double area() { return w * h; }
}
public class AbstractDemo {
public static void main(String[] args) {
Shape[] shapes = { new Circle(1), new Rectangle(3, 4) };
for (Shape s : shapes) System.out.println(s.describe());
// new Shape("x"); // doesn't compile: Shape is abstract
}
}Circle with area 3.14 Rectangle with area 12.00
Loading the rest of the lesson…