What is immutable class
Value of the
member variable can’t change once its set
What is the benefit of having immutable?
As immutable
class is read only, it can be used in multi-threading environment without
worrying about race condition
How to create a class as immutable
Goal : Create a
class, if you have created object for that class, then value should be changed
Let’s take a class
employee
Step 1: create
employee class
class employee{
private int emp_id;
private String emp_name;
private int emp_age;
}
Problem : Anyone can
declare public function through which can change the value of the variable.
Solution : Declare those variable as final, So that only
constructor can assign the value to the
variable
Step 2 : Declare member variable as final
class employee{
private final int emp_id;
private final String emp_name;
private final int emp_age;
public employee (int ID,String NAME , int age){
emp_id = ID;
emp_name = NAME;
emp_age = age;
}
}
Remember, if you are passing any object as an input param,
then that needs to be deep copied.
Problem : How to retrieve the value of the class
Solution: Add getter
method , scope is public
Step 3 : Add getter method to retrieve the value
public int getID(){
return emp_id;
}
public String getName(){
return emp_name;
}
Step 4 : declare class as final, So that it can’t be
inherited
public final class employee{
…
…
}
What are the immutable classes available in java ?
String class is the best example of the immutable
No comments:
Post a Comment