final public class ImmutableWithObject {
final Object obj;
final List myList;
ImmutableWithObject(Object obj1, List list)
{
this.obj = obj1;
this.myList = ((List) ((ArrayList) list).clone());
}
public Object getObj() {
return this.obj;
}
public List getMyList() {
return (List) ((ArrayList<String>) this.myList).clone();
}
public static void main(String[] args) {
ImmutableWithObject io = new ImmutableWithObject(new Date(), new ArrayList());
((Date) io.getObj()).setDate(22);
System.out.println((Date) io.getObj());
}
}
o/p : Mon Aug 22 00:50:04 IST 2011
which is incorrect.
Example to create Immutable class The instance variable of the class is final i.e. we cannot change the value of it after creating an object. The class is final so we cannot create the subclass. There is no setter methods i.e. we have no option to change the value of the instance variable.
To create a custom immutable class we have to do the following steps. Declare the class as final so it can't be extended. Make all fields private so that direct access is not allowed. Do not provide setter methods (methods that modify fields) for variables, so that it can not be set.
If you want to encapsulate a mutable object into an immutable one, then you need to: 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. Never return the mutable object.
Immutable objects are objects that don't change. You make them, then you can't change them. Instead, if you want to change an immutable object, you must clone it and change the clone while you are creating it. A Java immutable object must have all its fields be internal, private final fields.
Immutable means that once the object has been constructed, its state does not change.
From EJ Item 15 <-- Lot more information in there
Classes should be immutable unless there's a very good reason to make them mutable. If a class cannot be made immutable, limit its mutability as much as possible.
You cannot make it immutable since this object cannot create copies of the contents of the list or the Object. Assuming that you mean to have getters for accessing those properties, the properties themselves were created elsewhere and can be changed in code external to this class that has a reference to it.
The only exception to this is if the contents of Object and List are themselves immutable. Then you can create an immutable copy of the list and you would be done.
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