Immutable class/object, private Constructor, factory method

immutability, java, singleton

Solution

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.

Problem

Having already read how to make a class Immutable by following steps - Don't provide "setter" methods — methods that modify fields or objects referred to by fields. - Make all fields final and private. - 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. - If the instance fields include references to mutable objects, don't allow those objects to be changed: a. Don't provide methods that modify the mutable objects. b. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods. 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??

Original source

Related problems