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
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.