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()
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).
If you mean:
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:
as equivalent to:
In Java, the convention is to provide setters and getters to change an object's inner attributes. For your case:
The setter receives the new value and sets it:
And the getter gives access to the field's current value:
You cannot, however, overload the
=
operator to do assetBar
does, at least in Java. If you're thinking about, for example theInteger
orFloat
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.No, it goes against encapsulation logic, and Java Itself.
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.
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);