如果我有一个具有私有可见性的实例变量,我应该使用 setter 来更改其值,还是直接更改值?
此示例中的实例变量只会在此类中更改,因此 setter 将是私有的。我认为使用 setter 是正确的方法,因为它可以本地化更改的方式/时间,但它只是出于某种原因困扰着我!
请参阅下面的代码,这可能有助于更清楚地表达我的问题
public class A {
private int i;
public A() {
i = 5
}
private void doSomeCalculationsA() {
//work done here which results in the value of i being directly changed
i = 7
}
private void doSomeCalculationsB() {
//work done here which results in change value of i being changed via the setter
setI(5)
}
private void setI(int newValue) {
i = newValue;
}
}