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?
If the
privateconstructor 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 theabstractmodifier is in this case redundant—with or without it there would be no instantiation possible. As @JB Nizet notes below, theabstractmodifier is also bad practice because it sends wrong signals to the class’s clients. The class should in fact have beenfinal.There is another use case, quite rare though: you can have an
abstract classwith onlyprivateconstructors 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
privateconstructor. It gets used in anabstractclass just as in any other.