Search code examples
javaobjectprimitive-types

Is it possible to make a Java object 'reflect' a primitive type?


Let's say I have the following class:

public class Value
{
    private String label;
    private double value;

    public Value(String label, double value)
    {
        this.label = label;
        this.value = value;   
    }

    public double getValue()
    {
        return this.value;
    }
}

Now given the following instances:

Value v1 = new Value("first value", 5);
Value v2 = new Value("first value", 6);

Is there some way to alias

double sum = v1.getValue() + v2.getValue();

with

double sum = v1 + v2;

?

Classes like Double and Integer already have this functionality. So (how can we add it | why can't we add it) to our own classes?


Solution

  • We can't. In Java there's no possible way to overload the built-in operators.

    You mentioned that this is valid for the wrapper types (like Integer, Double, etc.), but this is not exactly true. When the operator is applied to such types, in the background a process, called un-boxing, is started, so that Double is turned to double, Integer to int and so on.