I have the following query , I was going through Java immutable class concept and come up with the following analysis..
- All the fields must be private and preferably final
- Ensure the class cannot be overridden – make the class final, or use static factories and keep constructors private
- Fields must be populated from the Constructor/Factory
- Don’t provide any setters for the fields
- Watch out for collections. Use Collections.unmodifiable*.
- Also, collections should contain only immutable Objects
- All the getters must provide immutable objects or use defensive copying
- Don’t provide any methods that change the internal state of the Object.
Now I have the following class..
public final class Bill {
private final int amount;
private final DateTime dateTime;
private final List<Integers> orders;
}
Please advise how it can be made as immutable class.
Your class as it is is immutable. Now you probably want to add a few methods:
Alternatively, you can use
this.orders = Collections.unmodifiableList(orders);in the constructor and return it from getOrders():return orders;, which enforces the fact that you should not modify that list, even within your class.