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 MyOrderDet
Why do you not just do?
public void increment() {
count++;
}
And what is the int parameter to the increment() function for?
a. If you just want to increment, you don't need to provide any setter.
b. In
public void increment() {
setCount(getCount() + 1);
}
You can directly access the count variable, so count++
is enough, doesn't need to setCount.
c. Usually need a reset method.
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;
}
}
So you can use the class like:
Counter counter = new Counter();
counter.increment() //increment the counter
int count = counter.getCount();