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