Add a private constructor to an abstract class

Please provide

  • Operating system: Windows 11
  • SonarLint plugin version: SonarLint for Eclipse
  • Programming language you’re coding in: Java 17
  • Is connected mode used: No, just Eclipse plugin with hightlighting

As the title says, it’s asking me to add a private constructor to an abstract class.
Abstract class cannot be instantiated so far as I know which makes no need for constructor.
Am I wrong?

Hi @H.Lo,

In your example, your class is meant to be a utility class since it only provides static fields. It is also abstract, so while it cannot be instantiated, it can still be extended because Java adds an implicit public constructor to every class.

In this case, the best practice is usually to declare a private constructor, that way, no one can subclass it or create an instance of it.

This is also described in the rule java:S1118:

Utility classes, which are collections of static members, are not meant to be instantiated. Even abstract utility classes, which can be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.