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 class, can I set it's value with myObject = 0;
public class foo{
private int bar;
public foo(){
}
}
Instead of creating a method public void setBar()
If you mean:
foo x = new foo();
x = 10; // This is meant to set x.bar
then no, you can't do that in Java. Good thing too, if you ask me... it would be horrible in terms of readability.
You also can't change it to allow:
foo x = 10;
as equivalent to:
foo x = new foo();
x.bar = 10; // Or x.setBar(10);
No you can't do that. Java does not support operator overloading. Although +
operator is overloaded for performing String concatenation, but that's the only exception. Another example that uses the =
operator the way you would want is in case of wrapper classes, where you can directly assign a primitive type values to it's corresponding wrapper type, which causes the primitive value to be auto-boxed to wrapper type.
Integer val = 10; // 10 is auto-boxed to Integer reference
But it's only limited for that purpose. You can't do that for your own user-defined type.
Creating a method is your only option.
Foo myObject = new Foo();
Here, myObject
holds the reference. You can't assign primitive value such as 0 to object references.
Instead, you should do myObject.setBar(10);
No, it goes against encapsulation logic, and Java Itself.
Abother possibility, you could make this field public. It would just need to do the validations you need in the business method (no during the set).
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.