Object-oriented programming series: 1. Classes, objects, access modifiers · 2. Immutability, equals/hashCode, final · 3. Inheritance, encapsulation, polymorphism · 4. Abstract classes and interfaces · 5. UML, class relationships · 6. Wrappers, BigDecimal, String
Can an object change after it’s created, when are two objects “equal”, and what does final lock? After this post you can write immutable classes, override equals/hashCode correctly, and explain why changing a constant breaks another service. Read part 1 first (classes, constructors, static).
At a glance:
flowchart TD
I[Immutable class] --> I1["private final, no setters"]
I --> I2[final class]
I --> I3[Defensive copies]
I --> R["record: shallow immutability"]
E[Override equals] -->|must| H[Override hashCode]
H --> HM["HashMap/HashSet work"]
FN[final] --> FR["Locks reference, not object"]
ST[static] --> SC["Class or object?"]
SF["static final constant"] -.->|trap| IN["Copied into callers"]
1. Immutable classes and objects
Key idea: an immutable object can be created and read, but never changed; a “modifying” operation returns a new object. That’s why threads can share it without locks.
- All fields are
private final. - No setters or other state-changing methods.
- The class is
final(or has private constructors), so subclasses can’t add mutable state. - Defensive copies (copy on the way in and out): mutable fields (
List,Date, arrays) are copied on the way in and never exposed directly on the way out.
public final class Customer {
private final String name;
private final List<String> tags;
public Customer(String name, List<String> tags) {
this.name = Objects.requireNonNull(name);
this.tags = List.copyOf(tags); // copied and unmodifiable
}
public String name() { return name; }
public List<String> tags() { return tags; } // safe, it's already immutable
public Customer withName(String newName) { // "modify" = create a new object
return new Customer(newName, tags);
}
}
Benefits: thread safety (correct under concurrent use) without locks, safe HashMap keys because the hash never changes, easier reasoning and caching.
Java 16+ gives you record: one line for an immutable class with a constructor, accessors, equals, hashCode and toString. Validation goes in the compact constructor (a short constructor that doesn’t repeat the parameters):
public record Money(BigDecimal amount, String currency) {
public Money { // compact constructor for validation
if (amount.signum() < 0) throw new IllegalArgumentException("amount < 0");
}
}
The slides’ Circle isn’t fully immutable
The slides’ Circle has private double radius and only a getter. No setter isn’t enough: to make it fully immutable, mark the field final (so the class itself can’t reassign it) and the class final (so subclasses can’t add state or mutating methods).
2. Object’s methods: toString, equals, hashCode
Key idea: every class inherits from java.lang.Object, so every class has these three methods. The defaults are nearly useless for value objects, and equals and hashCode are always overridden together.
| Method | Default | Override it to |
|---|---|---|
toString() |
Animal@1b6d3586 (class name plus a hex hash) |
ease logging and debugging, but never include sensitive data (passwords, tokens, card numbers) |
equals() |
compares references, like == |
compare contents for value objects (Money, Fraction, Email) |
hashCode() |
identity-based hash | match equals: equal objects, equal hashes |
The equals contract: reflexive (x.equals(x)), symmetric, transitive, consistent (same result on repeated calls), and x.equals(null) == false. toString() is called automatically when you print an object or concatenate it with a string.
JPA entities add their own twists (the id exists only after saving, Hibernate proxies), covered in the ORM and JPA post.
3. final in full
Key idea: final means “can’t change any more”; what gets locked depends on where you put it. It locks the reference, not the object it points to.
| Applied to | Meaning | Example |
|---|---|---|
| Local variable, parameter | Assigned exactly once | final int max = 10; |
| Instance field | Must be assigned exactly once, before the constructor finishes | private final String id; |
static field |
Assigned once when the class is initialized; static final is how you declare a constant |
static final int MAX_RETRY = 3; |
| Method | Subclasses can’t override it | public final String payslip() |
| Class | Nobody can extend it | final class String |
final and static aren’t opposites but independent axes: static = “class or object?” (saving memory is only a side effect), final = “can it be reassigned?”. static final is the most common combination: a class constant.
Three final points interviewers like: effectively final, the Java Memory Model, parameters
- A local variable used inside a lambda or an anonymous class must be
finalor effectively final (never reassigned after initialization), even without the keyword. - The Java Memory Model (the rules for what one thread sees of another’s writes) gives
finalfields a guarantee: once another thread sees the fully constructed object, it also sees the correct values of itsfinalfields (as long asthisdidn’t escape during construction). That’s why immutable objects are safe to share across threads. finalon a method parameter is mostly for readability; it has no effect on the caller, since Java always passes by value.
Exercises
Each prompt is a short paraphrase. All solutions were run on JDK 21.
1. A Fraction class
Requirements: a private numerator and denominator; a constructor, a method that reduces the fraction (dividing by the GCD), a method that returns the "a/b" string form, and add, subtract, multiply and divide methods that each return a new fraction; plus a main to try it out.
Solution to Exercise 1: an immutable Fraction class
public final class Fraction {
private final long numerator;
private final long denominator;
public Fraction(long numerator, long denominator) {
if (denominator == 0) throw new ArithmeticException("Denominator must not be zero");
if (denominator < 0) { // normalize: the sign always lives on the numerator
numerator = -numerator;
denominator = -denominator;
}
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction reduce() {
long g = gcd(Math.abs(numerator), denominator);
return g <= 1 ? this : new Fraction(numerator / g, denominator / g);
}
public Fraction add(Fraction o) {
return new Fraction(numerator * o.denominator + o.numerator * denominator,
denominator * o.denominator).reduce();
}
public Fraction subtract(Fraction o) { return add(new Fraction(-o.numerator, o.denominator)); }
public Fraction multiply(Fraction o) {
return new Fraction(numerator * o.numerator, denominator * o.denominator).reduce();
}
public Fraction divide(Fraction o) {
if (o.numerator == 0) throw new ArithmeticException("Cannot divide by a zero fraction");
return new Fraction(numerator * o.denominator, denominator * o.numerator).reduce();
}
private static long gcd(long a, long b) {
while (b != 0) { long t = a % b; a = b; b = t; }
return a;
}
@Override public String toString() {
return denominator == 1 ? String.valueOf(numerator) : numerator + "/" + denominator;
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Fraction other)) return false;
Fraction a = reduce(), b = other.reduce();
return a.numerator == b.numerator && a.denominator == b.denominator;
}
@Override public int hashCode() {
Fraction r = reduce();
return Objects.hash(r.numerator, r.denominator);
}
public static void main(String[] args) {
Fraction a = new Fraction(1, 2), b = new Fraction(3, 4);
System.out.println(a.add(b)); // 5/4
System.out.println(a.subtract(b)); // -1/4
System.out.println(a.multiply(b)); // 3/8
System.out.println(a.divide(b)); // 2/3
System.out.println(new Fraction(6, -8).reduce()); // -3/4
System.out.println(new Fraction(2, 4).equals(new Fraction(1, 2))); // true
}
}
Design decisions:
- Immutable: every operation returns a new object, like
BigDecimal. - A zero denominator is rejected: the invariant (a rule that must always hold) is enforced in the constructor.
- The sign is normalized: it always lives on the numerator.
equals/hashCodework on the reduced form, so2/4equals1/2.- With very large numerators and denominators the multiplications can overflow
long; then useMath.multiplyExactor switch toBigInteger.
Remember
- List the four steps of an immutable class, and why a record still needs
List.copyOf. - Explain why overriding
equalswithouthashCodemakesHashSet.containsreturnfalse. - Tell
==fromequals, and know when==is right (primitives, enums). - Say what
finallocks in each position, and why afinal Liststill accepts new elements. - Explain why changing a
static finalconstant in a library leaves another service on the old value.
Interview questions
Junior
Can you still add elements to a final List<String> items field?
Yes. final only forbids reassigning the reference; the underlying ArrayList is still mutable.
It’s items = new ArrayList<>() that won’t compile. If the contents must not change, assign an immutable list (List.copyOf, List.of) and never hand out a mutable one.
What’s the difference between == and equals?
== compares values for primitives and identity (is it the same object?) for references; equals compares content when the class overrides it.
- Classes that override
equals:String,Integer, records.Object’s default is just==. - Compare strings with
equals("a" == new String("a")isfalse); enums can use==because each constant is unique. - Write
"ACTIVE".equals(status)orObjects.equals(a, b)to avoid an NPE when a value may benull.
Mid
Why must you override hashCode when you override equals?
Because the contract says equal objects must have equal hash codes, and HashMap/HashSet find the bucket by hash before calling equals.
With different hashes, the objects land in different buckets, and contains/get give wrong answers even though the objects are “equal”.
How do you write an immutable class, and why are immutable objects useful?
private final fields, no setters, a final class, and defensive copies of mutable fields on the way in and out; or use a record (still copying collections).
Benefits: thread safety without locks, safe map keys, easier reasoning, cacheability, and free sharing.
How does a record differ from a hand-written immutable class? Is a record fully immutable?
A record generates everything an immutable class needs, but it’s only shallowly immutable: a mutable List component can still be modified.
- A record (Java 16) generates
private finalfields, a canonical constructor, accessors, andequals/hashCode/toStringover all components; the class is implicitlyfinaland can’t declare extra instance fields. - Validation and
List.copyOfgo in the compact constructor. - Records don’t suit JPA entities (no-arg constructor, proxies, mutable fields), but they’re great for DTOs, value objects and map keys.
Senior
Useful phrases for interviews
- “Since this is a value object, I override equals and hashCode together, or simply use a record.”
- “Immutable objects are thread-safe by design, so I default to them and opt into mutability only when needed.”
- “
finallocks the reference, not the object, so a final list can still be modified.” - “Primitive and String compile-time constants get inlined, so changing one means recompiling every class that uses it.”
- “A record gives me equals, hashCode and toString for free, but it’s only shallowly immutable, so I copy collections in the compact constructor.”
- “Two equal objects must have the same hash code; the reverse isn’t required.”
- “I make defensive copies on the way in and never hand out the internal mutable list.”
- “I keep secrets out of
toString, because it ends up in logs.”
Notes based on the Fundamentals of Backend course (Ronin Engineer) and the Hỏi Dân IT Java Core material, plus my own research, rewritten in my own words.