Immutable class in java

What is Immutable class in java?

Immutable class in java is that class of which once we create an object then we are not allowed to change the content or state of that object.

How to create Immutable class in java?

 Make your class as final (can’t extend further)

 Make data member as final (can’t change value further)

 Provide parameterized constructor

 Provide getter method for each field.

 Do not provide setter method

Java program to create immutable class / example to create immutable class in java :

public final class Test {

final int id;

public int getId() {

return id;

}

public Test(int id) {

this.id = id;

}

public static void main(String[] args) {

Test it = new Test(10);

System.out.println(it.getId());

}

}

Output : 10

There is no setter method provided in above example, so we have no option to change the value of instance variable.

Thanks for visiting Ajitation.com, Ajitation is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content.