Reputation: 851
According to Encapsulation fields should be private and public getter-setters.
But using setter there is a way that another class can alter the value of private field, So what should be the way to protect fields.
Please consider this class for discussion :
class Emp {
private String name;
private int age;
public Emp() {}
// getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Upvotes: 1
Views: 735
Reputation: 718758
If you don't want other classes to be able to change a field via a setter, simply don't provide the setter. Declaring the setter as private
has the same effect.
You said:
According to Encapsulation fields should be private and public getter-setters.
Actually, the key requirement for achieving encapsulation is to declare the fields as private
. That is what prevents other classes from "seeing" or depending on how the property is implemented. Providing getters and/or setters is optional.
Upvotes: 2
Reputation:
You could make the class immutable.
An immutable object is one that will not change state after it is instantiated.
final class Emp {
private final String name;
private final int age;
public Emp(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Making the class final ensures this class can not be subclassed. This subclass could potentially add mutability.
Upvotes: 4
Reputation: 3968
When you need the setters add some kind of control:
public void setName(String name) {
if (name == null) {
throw new IllegalArgumentException();
}
this.name = name;
}
When you use java beans it is also possible to use roles:
@RolesAllowed("Administrator")
public void setName(String nam) {
...
}
Upvotes: 0
Reputation: 4569
Pass data in constructors:
class Emp {
private String name;
private int age;
public Emp(String name, int age) {
this.name = name;
this.age = age;
}
// getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Upvotes: 0