How to create Immutable class in Java?

Immutable class means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like String, Boolean, Byte, Short) and String class is immutable. We can create our own immutable class as well.

Following are the requirements:
• Class must be declared as final (So that child classes can’t be created)
• Data members in the class must be declared as final (So that we can’t change the value of it after object creation)
• A parameterized constructor
• Getter method for all the variables in it
• No setters(To not have option to change the value of the instance variable)

Example to create Immutable class

// An immutable class

publicfinalclassStudent

{

finalString name;

finalintregNo;

publicStudent(String name, intregNo)

{

this.name = name;

this.regNo = regNo;

}

publicString getName()

{

returnname;

}

publicintgetRegNo()

{

returnregNo;

}

}

// Driver class

classTest

{

publicstaticvoidmain(String args[])

{

Student s = newStudent("ABC", 101);

System.out.println(s.name);

System.out.println(s.regNo);

// Uncommenting below line causes error

// s.regNo = 102;

}

}

Output :

ABC
101

In this example, we have created a final class named Student. It has two final data members, a parameterized constructor and getter methods. Please note that there is no setter method here.
(In order to make it functional, create objects of Student class in the main function.)

This article is contributed by Abhishree Shetty. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.