Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the return immutable in JAVA

I have an object such as

public class ABC {

    private String a;
    private String b;
    private String c;

    //getters and setters    
}

This object is returned from a method in the collections such as ArrayList<ABC>.

I just want to make the return immutable without changing anything in the object. Can anyone please help me with this?

like image 251
gagan Avatar asked Feb 02 '26 04:02

gagan


2 Answers

Don't provide setters (mutators), make immutable attributes private, only provide value assignment via constructor.

You can always declare your immutable attributes final. So you can only assign them values once and can't change them later.

like image 154
Murtaza Zaidi Avatar answered Feb 04 '26 16:02

Murtaza Zaidi


You cannot make an object immutable if its class provides for mutation. Objects always offer all the capabilities defined by their classes.

Therefore, if you want an immutable object then you need an immutable class. If you cannot change the class in question, then a wrapper class such as @duffymo described could serve that purpose. Note, however, that objects of such a class are not interchangeable with objects of the wrapped class, and also that somehow you need to provide for applying the wrappers.

If you need objects that are fully interchangeable with objects of class ABC, then you're stuck with the fact that ABCs are mutable, therefore anything interchangeable with ABCs is mutable, at least with respect to the mutable aspects of ABC. Then it comes down to why you want immutability. If the point is to avoid mutating the object referenced by the List, then copying those objects (to whatever depth is appropriate) is an alternative.

As a third alternative, if the target class has no non-private fields then you might be able to create a subclass, overriding the setters to be ineffective or to throw some variety of unchecked exception. In that case, note that

  1. Such a subclass is not good form, and its instances are not truly interchangeable with instances of class ABC.
  2. If class ABC has accessible properties of mutable types (e.g. mutable containers), then you may need to do something to prevent those objects from being mutated, too. Recursively.
  3. Yes, this is a big mess.
like image 45
John Bollinger Avatar answered Feb 04 '26 18:02

John Bollinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!