Getters and setters provide controlled access to private variables, enabling constraints on data manipulation. For instance:
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
if (name != null && name.length() > 2) {
this.name = name;
}
}
}
In this Person
class, the name
variable is private, accessible only through the getName()
and setName(String)
methods. The setName
method enforces constraints, allowing the name to be set only if it is not null and has a length greater than 2 characters. Similar constraints can be applied to the getter method:
public String getName() {
if (name.length() > 16) {
return "Name is too large!";
} else {
return name;
}
}
In the modified getName()
method, the name is returned only if its length is less than or equal to 16. Otherwise, "Name is too large" is returned. This approach prevents unwanted modifications by client classes.
Consider a class with getters and setters, like CountHolder
:
public class CountHolder {
private int count = 0;
public int getCount() {
return count;
}
public void setCount(int c) {
count = c;
}
}
Although the count
variable is private, the class provides public methods, getCount()
and setCount(int)
, for controlled access. One might question the necessity of getters and setters and propose making count
public:
public class CountHolder {
public int count = 0;
}
However, using getters and setters offers advantages such as encapsulation, allowing for controlled access, applying constraints, and facilitating potential future modifications without affecting external code. Direct access to variables may lead to a lack of control and hinder future enhancements.