Immutable class means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. We can create our own immutable class as well.
Following are the requirements:
- The 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 the option to change the value of the instance variable)
Example to create Immutable class
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 firstname.lastname@example.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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Java.util.BitSet class methods in Java with Examples | Set 2
- Shadowing of static functions in Java
- How does default virtual behavior differ in C++ and Java ?
- How are Java objects stored in memory?
- How are parameters passed in Java?
- Are static local variables allowed in Java?
- final variables in Java
- Default constructor in Java
- Assigning values to static final variables in Java
- Comparison of Exception Handling in C++ and Java
- Does Java support goto?
- Arrays in Java
- Inheritance and constructors in Java
- More restrictive access to a derived class method in Java
- Comparison of static keyword in C++ and Java
- Static blocks in Java
- Access specifiers for classes or interfaces in Java
- java.lang.Character class methods | Set 1
- Comparison of Inheritance in C++ and Java
- Output of Java Program | Set 1