Immutable Class in Java
intermediate· OOP · Encapsulation
Problem
An immutable class guarantees that once an object is created, none of its state can change — every field is set once, in the constructor, and never reassigned.
Create a Point class whose x and y coordinates can never change after construction.
Input
new ImmutablePoint(3, 4)
Output
Point: (3, 4)
Java Program
Java
public class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
public static void main(String[] args) {
ImmutablePoint p = new ImmutablePoint(3, 4);
System.out.println("Point: (" + p.getX() + ", " + p.getY() + ")");
}
}Output
Point: (3, 4)
Core Logic
Marking every field private and final, and providing only getters — no setters — makes it impossible for any code outside the constructor to change an object's state.
How It Works
- 1
private final int x, y;declares both fields so they can only be assigned once, and only from within the class. - 2The constructor is the only place either field is ever assigned —
this.x = x; this.y = y;— and there's no method anywhere that reassigns them afterward. - 3Only getter methods (
getX(),getY()) are provided — there are no setters at all, so external code has no way to mutate an existing object. - 4Once
new ImmutablePoint(3, 4)returns, that specific object's coordinates are fixed for its entire lifetime.
Printing the point right after construction always reports the same (3, 4) — nothing in the class provides a way to change it.
💡
Key Point: If a field were a mutable object (like an array), true immutability would also require defensively copying it in the constructor and any getter — this class avoids that concern entirely by sticking to primitive fields.
Key Concepts
private final fieldsno settersconstructor-only initialization