使用getter setter增加int值
我需要增加int值。 所以我为它做了getter / setter,我将这个逻辑应用于int的增量值:
public class MyOrderDetails { private int count = 0; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public void increment(int increment) { setCount(getCount() + 1); } }
这是正确的方式,我正在做什么或这是专业语法错误?
一个。 如果您只想增加,则无需提供任何setter。
湾 在
public void increment() { setCount(getCount() + 1); }
你可以直接访问count变量,所以count++
就足够了,不需要setCount。
C。 通常需要一个重置方法。
d。 count ++不是primefaces的,因此如果在multithreading场景中使用它,则同步。
public synchronized void increment() { count++; }
所以最后课程将是:
class Counter{ private int count = 0; public int getCount(){ return count; } public synchronized void increment(){ count++; } public void reset(){ count = 0; } }
所以你可以使用这样的类:
Counter counter = new Counter(); counter.increment() //increment the counter int count = counter.getCount();
你为什么不这样做?
public void increment() { count++; }
对于increment()函数,int参数是什么?