Search code examples
javaoperator-overloadingjava-6

Change the default behavior of my own classes to output value


I am creating a mini class in Java:

public class ObjectInfo {
    public Object value = null;
    public Boolean isMax = null;
}

I want to make it so this class will output value whenever I call an instance.

Example:

public final void testSomething() {
    ObjectInfo actual = new OjbectInfo(11f, true);
    assertEquals(11f, (Float) actual);
}

I would like to make the class such that when I call actual like above, it knows to extract out the value parameter.

Is there any way to do this?

What I'd also like to do is say

actual = 1234f

I would like Java to know to shove that value into value and

actual = false

Put that into isMax

I know this can be done in C++ with operator overloading, but I can't seem to find anything on it for Java, at least on Google...


Solution

  • You cannot do this in Java. Instead you should add setter and getter methods or the properties you want to access. For example #setFloat( float value ) and #getFloat(). Then write test something like this:

    assertEquals( 11f, actual.getFloat() );