I know how to create a immutable class
. I created the following .
public class Employee {
private final int id;
private final String name;
private final int salary;
public Employee(int id, String name, int salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getSalary() {
return salary;
}
}
Few articles also suggests that, you declare your class as final
, even Effective JAVA book says "mark your methods as final so that they can not be overriddden" . But I am not able to understand why I need to use final
on class or on setter
methods, when the fields are declared private
and also final
?
Or the articles and EFFECTIVE JAVA suggesting an alternative approach !!!