Class With All Private Constructors Should Be Final
ID |
java.final_class_should_have_private_constructor |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
code-style, reliability |
Description
Reports classes where all declared constructors are private but the class itself is not declared final.
Rationale
When every constructor in a class is private, no external code (including subclasses) can instantiate it. The class is effectively sealed, yet the absence of final suggests it was designed for extension. This contradiction confuses readers and may hide design intent.
// Bad -- cannot be subclassed but not declared final
public class Utility {
private Utility() {}
public static void doWork() {}
}
Remediation
Add final to the class declaration if the class is intentionally non-extensible (the common case for utility classes and singletons). If extension is intended, provide at least one protected or package-private constructor.
// Good -- explicitly final
public final class Utility {
private Utility() {}
public static void doWork() {}
}