Open tongshen9095 opened 4 years ago
Q: Does every private field need a getter and a setter? A: No.
Q: Difference between the following two methods?
A: We can set control number range in setNumber()
// method 1
public int number;
// method 2
private int number;
public void setNumber(int num) {
this.number = num;
}
Q: Private field, without setter A: Read-only variable. Initialize with the constructor.
Getter and Setter - DZone
The class declares a private field, number. Since
number
is private, the code from the outside of this class cannot access the variable directly.Instead, the outside code has to invoke the getter,
getNumber()
, and the setter,setNumber()
, in order to read or update the variable.By using getter and setter, the programmer can control how their important variables are accessed and updated in the proper manner, such as changing the value of a variable within a specified range.