Having already read how to make a class Immutable by following steps
AM not sure I clearly understand the utility of private constructor and factory method in the context of immutability. If I make class final, basically am closing all paths of any other class extending it. How is the stated a more sophisticated approach
I have seen private constructor,factory method in Singleton pattern which makes sense. But when we talk of object immutability, are we also restricting object construction/instantiation when we mention private constructor and static factory methods??
After thoroughly reading the below point
Dont allow subclass to over ride methods. The simplest way to do this is to declare the class final. A more sophisticated approach is to make constructor private and construct instances in factory method.
I think the point here is not
Making class final and private constructor.
The point is
Either you make your class final or have a private constructor.
Hope it helps!!
source
Firstly, there are several reasons why immutable class generally should not be overriden, you can find them here.
That said, making a constructor private is just one way to prevent class from being overriden. Why? Because in sub-class, every constructor (implicitly) calls super()
, a default constructor of base class. But if you make this constructor private, sub-class cannot call it and thus cannot override the base class. This approach is very suitable when you want to control the total number of instances of particular class, for example in case of singletons.
I think the big issue here is future refactoring. Suppose, in a later version, you find it would make something much simpler if you could split out some new special case of MyClass into a subclass, MySpecialClass.
If MyClass were a mutable class with a public constructor, you could just do it and tell users of the new features to create a new MySpecialClass. Existing uses are not affected.
If MyClass has a private constructor and a factory method, there is no problem. You declare MySpecialClass nested in MyClass, also with a private constructor. Add and/or modify the factory methods to choose which to create, but make sure existing calls go on working compatibly.
What would you do if MyClass were immutable, and final, but had a public constructor?
Yeah, you are right. It does not make any sense to make constructor private. By doing this, we are restricting the instance creation, which is not a desired scenario for immutability.
In example mentioned in sun site does not make constructor private http://docs.oracle.com/javase/tutorial/essential/concurrency/syncrgb.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With