Set custom class object's value with '=' operator in Java

前端 未结 6 2031
滥情空心
滥情空心 2021-01-19 01:31

I have a custom object that has a single value of type int that I wanting to do processing on to keep this value in a set range. My question is this: Given the following cla

6条回答
  •  执笔经年
    2021-01-19 02:21

    In Java, the convention is to provide setters and getters to change an object's inner attributes. For your case:

    foo instance = new foo();
    instance.setBar(10); //Sets bar to 10
    instance.getBar(); //returns bar's current value (right now 10)
    

    The setter receives the new value and sets it:

    public void setBar(int newBar) {
        bar = newBar;
    }
    

    And the getter gives access to the field's current value:

    public int getBar() {
        return bar;
    }
    

    You cannot, however, overload the = operator to do as setBar does, at least in Java. If you're thinking about, for example the Integer or Float wrapper classes, there's another force at work there, related to Java's implementation itself and that later derives in the concepts of boxing and unboxing.

提交回复
热议问题