user2686559 user2686559 - 1 month ago 10
Java Question

Why there is no keyword for declaring a class immutable in java?

Suppose you have an instance of MyClass myClass1.

It would be good to know with certainty if

MyClass class2 = class1;

creates new instance or not...

Answer Source

class1 and class2 both are reference variables and not the actual object. Suppose initially you made an intialization on MyClass as

MyClass class1 = new MyClass();

This will create an object of MyClass in the heap and variable class1 will point to that object. class1 itself will have no identity on the heap, rather it will be a part of stack holding a reference to MyClass object.

MyClass class2 = class1;

It definitely does not create any new instance of MyClass on the heap. The above line of code simply assigns the memory reference of MyClass object to variable class2. Now both class1 and class2 hold a reference to the same object of MyClass in heap. class1 and class2 themselves will be placed in the stack.

To achieve effects of immutability in java for a class you can explore more about the Singleton design pattern.