This repository demonstrates how to create an immutable class in Java using a Person class as an example.
Immutability means that once an object is created, its state cannot be changed. Instead of modifying an existing object, you create a new one with the updated data. Immutable objects are widely used in Java and functional programming for many reasons:
- β Thread-safe: No synchronization needed as data canβt change.
- β Safe for caching & sharing: Can be reused freely without side effects.
- β Reliable and predictable: No accidental data changes after construction.
- β Easy to debug: Object state remains consistent and traceable.
- β
Used in collections: Ideal for keys in hash-based collections like
HashMap.
- String Class
- Wrapper Classes (Integer,Long, Double, Float, Short, Byte,Boolean, Character)
- LocalDate,LocalDateTime,LocalTime (Part of Java8 Date-Time Api)
- BigDecimal, BigInteger
To create an immutable class, follow these rules:
- Declare the class as
finalso it can't be subclassed. - Make all fields
privateandfinal. - Donβt provide setters for any field.
- Initialize all fields through the constructor only.
- For mutable fields (like
List,Map,Date), return defensive copies.
src/ βββ com/self/immutablity/ βββ Person.java // Immutable class βββ TestImmutableClass.java // Test class to demonstrate immutability
Personclass is markedfinal(can't be subclassed)- Fields are
privateandfinal - No setters
- Uses defensive copying for mutable fields like
List - All fields initialized only in the constructor
A defensive copy is used to protect internal state:
this.hobbies = new ArrayList<>(hobbies); // In constructor
return new ArrayList<>(hobbies); // In getter