Tuesday, March 18, 2014

Java Mutable and Immutable objects
Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created.
A very simple immutable object is a object without any field. (For example a simple Comparator Implementation).
class Mutable{
  private int value;

  public Mutable(int value) {
     this.value = value;
  }

  getter and setter for value
}

class Immutable {
  private final int value;

  public Immutable(int value) {
     this.value = value;
  }

  only getter
}
Example
Mutable objects can have their fields changed after construction. Immutable objects cannot.
public class MutableClass {

 private int value;

 public MutableClass(int aValue) {
  value = aValue;
 }

 public void setValue(int aValue) {
  value = aValue;
 }

 public getValue() {
  return value;
 }

}

public class ImmutableClass {

 private final int value;

 public MutableClass(final int aValue) {
  //The value is set. Now, and forever.
  value = aValue;
 }

 public final getValue() {
  return value;
 }

}

No comments: