问题描述
我要求增加int值。所以我为它做了getter / setter,我将这个逻辑应用于int的增量值:
I have a requirement to increment int value. So I have made getter/setter for it and I applied this logic for the increment value of 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);
}
}
这是正确的方式我是什么做或者这个在语法上是错误的吗?
Is this right way what I am doing or is this pro grammatically wrong?
推荐答案
a。如果您只想增加,则无需提供任何setter。
a. If you just want to increment, you don't need to provide any setter.
b。在
public void increment() {
setCount(getCount() + 1);
}
你可以直接访问count变量,所以 count ++
就够了,不需要setCount。
You can directly access the count variable, so count++
is enough, doesn't need to setCount.
c。通常需要重置方法。
c. Usually need a reset method.
d。 count ++不是原子的,所以如果它在多线程场景中使用则同步。
d. count++ is not atomic, so synchronize if it is used in multi-threading scenario.
public synchronized void increment() {
count++;
}
所以最后这个课程将是:
So finally the class would be:
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();
这篇关于使用getter setter增加int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!