Private constructor in abstract class

Viewed 16371

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?

7 Answers

A private constructor in an abstract class can also serve the purpose of sealed classes (like in Scala or Kotlin etc.). Since you can still provide subclasses from within the abstract class, but outsiders cannot extend/implement (as @Marko Topolnik answered).

It does look like we will be getting sealed interface to more cleanly support this. See https://openjdk.java.net/jeps/8222777

A final class with only private constructors is a design used by singletons and multitons.

An abstract class which has only private constructors is the only way I've seen to prevent a class from being instantiated. I have seen it used to create utility classes (which only have static methods and/or members).

As for setting up user expectations I see that https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html states "Abstract classes cannot be instantiated, but they can be subclassed." I note that it does not state any intention that they are expected to be subclassed.

I also note however that viewing some Java source code I find the following designs are used (none of which are abstract classes with only private constructors):

Related