Incrementing int value using the getter setter

后端 未结 2 969
粉色の甜心
粉色の甜心 2021-01-23 06:58

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         


        
相关标签:
2条回答
  • 2021-01-23 07:31

    Why do you not just do?

    public void increment() {
        count++;
    }
    

    And what is the int parameter to the increment() function for?

    0 讨论(0)
  • 2021-01-23 07:37

    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();
    
    0 讨论(0)
提交回复
热议问题