Nimrod Nimrod - 1 year ago 50
Java Question

Why making the constructor private prevent subclasses to override methods on the parent?

When we want to define immutable objects there are serveral steps to follow.
The 3rd one on Oracle's site is:

Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.

How making the constructor private is equivalent declaring the class as final?


Imagine a class whose only constructor is private. Or whose all constructors are private.

Imagine you subclass this class.

How do you construct an instance of this subclass now?

In a subclass, you have to call any of the super constructors in every constructor of the subclass (either explicitly, or use implicit super() no-arg call). As you see, you can't do that if all constructors of the base class are private (inaccessible to subclasses). Because of that, it's an efficient way to prevent subclassing – or, to see it at a different way, to prevent to have working and usable subclasses.