Java Immutable class is, once the object is initiated, none of the fields can have its value changed.

Configuration
Java Compilation:
Java Runtime:
JDK 11.0.12
JRE HotSpot 11.0.12
Immutable class is, once the object is initiated, none of the fields can have its value changed
To create an immutable class in Java, we have to add the modifier final to the fields, so that they could not be changed after initiated by constructor:
public class MyImmutableClass { final private int age; final private String name; public MyImmutableClass(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } }
Using in main class:
public static void main(String[] args) { MyImmutableClass myImmutableClassPeter = new MyImmutableClass(30, "Peter"); System.out.println(myImmutableClassPeter.getName() + "'s age = " + myImmutableClassPeter.getAge()); }
Once the object myImmutableClassPeter is initiated, the value of its field can never be changed, assignment to any final field after constructor will lead to compile error. But of course reading is fine.
Output:
Peter's age = 30
If we assign a value other than the constructor:
public class MyImmutableClass { final private int age; final private String name; public MyImmutableClass(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } public void setAge(int age) { this.age = age; } }
There will be compilation error:
cannot assign a value to final variable age