How would you handle a mutable reference in immutable class?

How would you handle a mutable reference in immutable class?

If you want to encapsulate a mutable object into an immutable one, then you need to:

  1. Create a copy of the mutable object (i.e. via copy constructor, cloning, serialization/deserialization, etc.); never store the reference to the original mutable object.
  2. If you must to, then return a copy of the object.

What is mutable and immutable class?

A mutable object can be changed after it’s created, and an immutable object can’t.

How to create immutable class with reference of mutable class?

The way you’d do that would be to subclass Address and make all its setters throw a runtime exception, then constructor your subclass with a reference to a passed-in Address. But that’s a hack, better to create the new, truly immutable class. You need to create an immutable copy of your Address class and use that in the Employee class.

Can a field be changed in an immutable class?

Above class is immutable as we can not change field values after object creation. Now, lets assume that there is a change in requirement and instead of storing address in String object, we have to store it in more organized way.

Can you break immutability of user class in Java?

As of now all the fields of User class were String and String itself is immutable. But Address class has setter methods and hence now User class has one mutable member field. Can this break immutability of User class? Lets try to break immutability of User class. Here, first we got reference of address object using getAddress () method.

Why are all properties of an immutable object final?

A thread-safe immutable object is seen as immutable by all threads, even if a data race is used to pass references to the immutable object between threads. This can provide safety guarantees against misuse of an immutable class by incorrect or malicious code. final fields must be used correctly to provide a guarantee of immutability.