All 15 Interfaces & Abstract Classes questions
More in Interfaces & Abstract Classes
Advertisement
Back to results for “Design Patterns in Java”
Java › Interfaces & Abstract Classes

What is the purpose of declaring an abstract class with a protected constructor, and how does this pattern communicate the class's intended usage to other developers?

Intermediate

Answer

A protected (rather than public) constructor on an abstract class communicates that the class is intended to be extended (its constructor called only via a subclass's super() call) rather than directly instantiated -- though an abstract class can never be instantiated directly regardless of its constructor's access level (the compiler already prevents `new AbstractClass()` entirely), an explicit protected constructor still serves a valuable documentation/intent-signaling purpose and additionally restricts which OTHER classes can even see and call the constructor via reflection or from unrelated packages, reinforcing the class's intended 'to be extended, not directly used' role.
public abstract class Shape {
    protected final String name;

    protected Shape(String name) {  // protected: intended only to be called by subclasses via super()
        this.name = name;
    }

    public abstract double area();
}

public class Circle extends Shape {
    private final double radius;
    public Circle(double radius) {
        super("Circle");  // calling the protected constructor from a subclass
        this.radius = radius;
    }
    public double area() { return Math.PI * radius * radius; }
}
Real-world example A framework's abstract base class uses a protected constructor specifically to signal to library consumers that this class is meant to be extended with custom subclasses, not used directly, reinforcing this intent beyond what the already-enforced 'can't instantiate an abstract class directly' compiler rule alone communicates.

Common follow-ups: Given the compiler already prevents direct instantiation of an abstract class, what practical difference does the constructor's access modifier actually make?;How does this protected-constructor convention relate to the broader API design principle of clearly signaling intended usage patterns?