Private constructor in abstract class

Chris picture Chris · Jul 24, 2012 · Viewed 13.2k times · Source

In Java what is the purpose of using private constructor in an abstract class?

In a review I got this question, and I am curious, for what situation we need to use the constructor in such way?

I think it can be used in pair with another constructor in abstract class, but this is very trivial. Also it can be used for constructing static inner classes which will excend abstract class.

Maybe there is more elegant usage?

Answer

Marko Topolnik picture Marko Topolnik · Jul 24, 2012

If the private constructor is the only constructor of the class, then the reason is clear: to prevent subclassing. Some classes serve only as holders for static fields/methods and do not want to be either instantiated or subclassed. Note that the abstract modifier is in this case redundant—with or without it there would be no instantiation possible. As @JB Nizet notes below, the abstract modifier is also bad practice because it sends wrong signals to the class's clients. The class should in fact have been final.

There is another use case, quite rare though: you can have an abstract class with only private constructors that contains its own subclasses as nested classes. This idiom makes sure those nested classes are the only subclasses. In fact, enums in Java use just this idiom.

If there are other constructors around, well then there's really nothing special about the private constructor. It gets used in an abstract class just as in any other.