Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java Immutability
/**
* Created by anjana
*/
import java.util.Date;
/**
* Steps for making a class immutable:
* 1. Declare the class as final
* 2. Make all its fields final
* 3. For all mutable fields, class should make a defensive copy and only return the copy to the calling code
* 4. Do not provide any setter methods.
*/
public final class ImmutableClass {
/**
* Integer and String classes are immutable whereas Date class is mutable
*/
private final Integer immutableInteger;
private final String immutableString;
private final Date mutableDate;
public ImmutableClass(Integer i, String s, Date d) {
this.immutableInteger = i;
this.immutableString = s;
this.mutableDate = new Date(d.getTime());
}
public String getImmutableString() {
return immutableString;
}
public Integer getImmutableInteger() {
return immutableInteger;
}
public Date getMutableDate() {
return new Date(mutableDate.getTime());
}
@Override
public String toString() {
return immutableInteger + ", " + immutableString + ", " + mutableDate;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment