Skip to content

Instantly share code, notes, and snippets.

@anjanashankar9
Last active February 20, 2016 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anjanashankar9/b469aab4be5cbcb0413d to your computer and use it in GitHub Desktop.
Save anjanashankar9/b469aab4be5cbcb0413d to your computer and use it in GitHub Desktop.
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