The Plain Picture#
Two different promises:
"This address card will always point to the same house" — but you can still repaint the house.
"This house can never be changed" — once built, it stays exactly as it is.
The Real Names#
finalon a variable means the variable can't be reassigned. For a reference, the reference is fixed — the object it points to can still change:Java final Student fixed = new Student("Aisha", 100); fixed.score = 200; // allowed — the object is mutable System.out.println(fixed.score); // 200 fixed = new Student("X", 1); // compile error — the reference is finalAn immutable object is one whose state can never change after construction. To make a class immutable:
make all fields
private final(privateis explained in Object-Oriented Programming — it hides a field from outside code);set them only in the constructor;
provide no methods that change them;
if a field refers to a mutable object (like an array or list), don't hand it out directly — give back a copy.
Java final class QuizResult { // final class = can't be extended (03_java_oop.md) private final String student; private final int points; QuizResult(String student, int points) { this.student = student; this.points = points; } String student() { return student; } int points() { return points; } QuizResult withBonus(int extra) { // "changing" returns a NEW object return new QuizResult(student, points + extra); } }(Java 16+ records write all of this in one line —
record QuizResult(String student, int points) {}— covered in Object-Oriented Programming and Modern Java.)
Why immutability is valuable: an immutable object can be shared freely — between methods, and between threads (no race conditions,
Operating Systems Ch 8) — because nobody can change it underneath you. It's also safe to use as a key in a hash map
(Collections, From the Inside). The most important immutable class in Java is String.
Check yourself
3 questionsDoes final Student s = ...; stop you changing s.score?
Show answerHide answer
No — final only stops s being reassigned; the object is still mutable.
List the four rules for an immutable class.
Show answerHide answer
All fields private and final; set only in the constructor; no mutating methods; defensively copy mutable fields in and out.
How does an immutable object "change"?
Show answerHide answer
It doesn't — methods return a new object with the new values (like withBonus).