1

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?

Jonas Bartkowski
  • 357
  • 1
  • 6
  • 15
  • 1
    i guess you are looking for something like [this](http://stackoverflow.com/questions/3598707/operator-overloading-and-overriding-in-java)? – SomeJavaGuy Mar 11 '15 at 14:19
  • 2
    This would be overloading of operators, which you cannot do in Java. – stuXnet Mar 11 '15 at 14:20
  • 3
    "Classes like Double and Integer already have this functionality." Not really. They have auto-unboxing and auto-boxing functionality, that's all. – Jon Skeet Mar 11 '15 at 14:20
  • 1
    "Classes like Double and Integer already have this functionality." That's because they get an unfair help from Java compiler. – Sergey Kalinichenko Mar 11 '15 at 14:21
  • @JonSkeet Try to unbox your terms the next time; That way they can provide information that does explain the problem's context without providing references of unknown compatibility. – Jonas Bartkowski Mar 11 '15 at 14:36

2 Answers2

3

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.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
2

As others have mentioned this is called operator overloading and is not supported by Java. Also it's not to be confused with default unboxing of Integer and Double.

If calling getter methods on objects is a big issue for you i suggest you create a coupld of methods like:

private double add(Value... values){
    double sum = 0;
    for(Value val: values) 
        sum += val.getValue();
    return sum;
}
private double multiply(Value... values){
    double product = 1;
    for(Value val: values) 
        sum *= val.getValue();
    return product;
}

and so on...

So now you can do

double sum = add(v1,v2,v3,v4);
double product = multiply(v1,v2,v3);

and so on...

I think this is the closest thing to what you asked.

gkrls
  • 2,618
  • 2
  • 15
  • 29