Abstract Class Constructors Should Not Be Public

ID

java.abstract_class_constructor_not_public

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

code-style

Description

Reports public constructors declared in abstract classes. Since abstract classes cannot be instantiated directly, their constructors should be protected (or package-private) instead.

Rationale

A public constructor on an abstract class is misleading because the class can never be instantiated with new. The constructor is only invoked via super(…​) in a concrete subclass, so protected is the correct visibility. Using protected documents the intended usage and prevents accidental attempts to construct the abstract class.

// Bad -- public constructor on abstract class
abstract class Shape {
    public Shape(String name) {
        this.name = name;
    }
}

// Good -- protected constructor
abstract class Shape {
    protected Shape(String name) {
        this.name = name;
    }
}

Remediation

Change the constructor visibility from public to protected.