HOW TO MAKE CLASS IMMUTABLE?
IMMUTABLE CLASS IS THE CLASS WHICH WE CANNOT CHANGE THE VALUES IF ONCE DEFINED IN THAT CLASS.
THIS CAN BE ACHIEVED BY FOLLOWING WAY:
1.CREATING FINAL CLASS
2.DECLARING VARIABLES ONLY THROUGH CONSTRUCTORS
3.MEMBERS OF A CLASS SHOULD BE MADE WITH FINAL AND PRIVATE
4.DONT CREATE ANY SETTERS
5 DONT CREATE ANY METHODS THAT MODIFY MUTABLE CLASS
LET US SEE AN EXAMPLE:
IMMUTABLE CLASS IS THE CLASS WHICH WE CANNOT CHANGE THE VALUES IF ONCE DEFINED IN THAT CLASS.
THIS CAN BE ACHIEVED BY FOLLOWING WAY:
1.CREATING FINAL CLASS
2.DECLARING VARIABLES ONLY THROUGH CONSTRUCTORS
3.MEMBERS OF A CLASS SHOULD BE MADE WITH FINAL AND PRIVATE
4.DONT CREATE ANY SETTERS
5 DONT CREATE ANY METHODS THAT MODIFY MUTABLE CLASS
LET US SEE AN EXAMPLE:
public final class FinalPersonClass {
private final String name;
private final int age;
public FinalPersonClass(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
private final int age;
public FinalPersonClass(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
No comments:
Post a Comment