To create an immutable class, you should consider below points:
- Declare the class as final so that no one will extend the class.
- Declare all the variables in the class as final so that no one can change the value of the variables.
- Declare all variables as private so that others can not access directly.
- Do not write setter methods so that others can not modify the actual value of the variables.
- Write the parameterized constructor.
Example of Immutable Class :
public final class ABC {
private final int id;
private final String name;
private final String address;
public ABC(int id, String name,String address) {
this.name = name;
this.id = id;
this.address = address;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
}
Use of Immutable Class :
class Test
{
public static void main(String args[])
{
ABC abc = new ABC(1,"PQRS", "Pune");
System.out.println(abc.id);
System.out.println(abc.name);
System.out.println(abc.address);
}
}
private final int id;
private final String name;
private final String address;
public ABC(int id, String name,String address) {
this.name = name;
this.id = id;
this.address = address;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
}
Use of Immutable Class :
class Test
{
public static void main(String args[])
{
ABC abc = new ABC(1,"PQRS", "Pune");
System.out.println(abc.id);
System.out.println(abc.name);
System.out.println(abc.address);
}
}
No comments:
Post a Comment