How to create an Immutable class ?
What is an immutable class in Java?
Immutable objects are instances whose state doesn’t change after it has been initialized.
There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String classes are immutable. We can also create our own immutable class by creating a final class that has final data members.
How to create an Immutable class ?
Rules for creating Immutable class in Java−
Make class final − class should be final so that it cannot be extended.
Make each field final & private − Each field should be final so that they cannot be modified after initialization.
Create a getter method for each field. − Create a public getter method for each field. fields should be private.
No setter method for each field. − Do not create a public setter method for any of the fields.
Create a constructor − Such a constructor will be used to initialize properties once.
Comments
Post a Comment