Wednesday, February 20, 2013

Java Immutable Objects


What are immutable objects? What are their Advantages? Design a immutable object with Date object as a member attribute.

An object is considered immutable if its state cannot change after it is constructed.

Advantages :
1. Simple and Reliable Code.
2. Useful in concurrent Applications since they cannot change state, they cannot be corrupted by thread interference or present in inconsistent state.
3. Decreased overhead in Garbage Collection.
4. Reduction in code needed to protect objects in concurrent applications.

JDK Examples : String, Integer

public class Mydate {
private final Date date; // Declare the variable as final

public Mydate(Date date) {
this.date = new Date(date.getTime());
}
public getDate() {
return new Date(date.getTime()); // Need to return a copy instead of original object
}

// Note: No Setter method for date
}