Immutable class is the class whose value cannot be changed throughout the life cycle.
Ex:String
We cannot change the content of String class, everytime new reference is created when we change the content.
To create custom immutable class in java
- Class should be made final so that no class can extend it.
- Declare all variables as final
- Provide constructors to set the values
- There should not be any public set method which can change the state of
the object. - provde getter method
package com.usr.general;
final class Person {
final int age;
final String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
public class ImmutableDemo {
public static void main(String[] args) {
Person p = new Person(38, "sachin");
System.out.println(p.age);
System.out.println(p.name);
}
}
OUTPUT
38
sachin