Lecture-9 Immutable Classes
Lecture-9 Immutable Classes
4-2
Immutable Classes
• immutable: Unable to be changed (mutated).
– Basic idea: A class with no "set" methods (mutators).
• In Java, Strings are immutable.
– Many methods appear to "modify" a string.
– But actually, they create and return a new string (producers).
4-3
"Modifying" strings
• What is the output of this code?
String name = "pakistan";
name.toUpperCase();
System.out.println(name);
• The code outputs pakistan in lowercase.
• To capitalize it, we must reassign the string:
name = name.toUpperCase();
– The toUpperCase method is a producer, not a mutator.
If Strings were mutable...
• What could go wrong if strings were mutable?
public Employee(String name, ...) {
this.name = name;
...
}
}
Immutable methods
// mutable version
public void add(Fraction other) {
numerator = numerator * other.denominator
+ other.numerator * denominator;
denominator = denominator * other.denominator;
}
// immutable version
public Fraction add(Fraction other) {
int n = numerator * other.denominator
+ other.numerator * denominator;
int d = denominator * other.denominator;
return new Fraction(n, d);
}