How to write immutable class in Java
Some points we need to follow, which helps to make a class immutable in Java :
1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Class should be final in order to restrict sub-class for altering immutability of parent class.
So our immutable class have all private and final variables and a constructor to initialize the variables during object creation. All final variables can be initialized inside constructor only once during object creation that can't be changed latter. our immutable class does not provide setter method but have only getter method to access the initialized variables.
Some points we need to follow, which helps to make a class immutable in Java :
1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Class should be final in order to restrict sub-class for altering immutability of parent class.
So our immutable class have all private and final variables and a constructor to initialize the variables during object creation. All final variables can be initialized inside constructor only once during object creation that can't be changed latter. our immutable class does not provide setter method but have only getter method to access the initialized variables.
So our immutable class have all private and final variables and a constructor to initialize the variables during object creation. All final variables can be initialized inside constructor only once during object creation that can't be changed latter. our immutable class does not provide setter method but have only getter method to access the initialized variables.
Example
Simplest approach for making a class immutable, including it's making final class to avoid putting immutability at risk due to Inheritance and Polymorphism.
public final class Contacts {
private final String name;
private final String mobile;
public Contacts(String name, String mobile) {
this.name = name;
this.mobile = mobile;
}
public String getName(){
return name;
}
public String getMobile(){
return mobile;
}
}
No comments:
Post a Comment