Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this function call itself or call the overload?

Consider two overloads:

public void add(Integer value)
{
    add(value == null ? null : value.doubleValue());        
}

and

public void add(Double value)
{
    // some code here
}

If I call the first one with a null instance of an Integer, then does the ternary conditional call the overload to a Double, or does it call itself?

On my machine it calls the Double overload, but is this well-defined Java? And what does the JLS say about this?

like image 311
Fitzwilliam Bennet-Darcy Avatar asked Apr 19 '17 15:04

Fitzwilliam Bennet-Darcy


People also ask

How do you call an overloaded function?

Overloading of function-call operator in C++ The function call operator is denoted by “()” which is used to call function and pass parameters. It is overloaded by the instance of the class known as a function object.

What happens when you overload a function?

Using the function overloading concept, we can develop more than one function with the same name, but the arguments passed should be of different types. Function overloading executes the program faster. Function overloading is used for code reusability and to save memory.

Which function overloads the OR () function?

Explanation: The function __or__() overloads the bitwise OR operator |.

Why is it called an overload?

To overload is to load an excessive amount in or on something, such as an overload of electricity which shorts out the circuits. Overloading causes a "Too much!" situation.


1 Answers

Yes, it's well defined that it will call the Double overload. It couldn't call the Integer overload because there's no implicit conversion from double (which is the type of the conditional expression) to Integer.

Basically, there are two parts of this that are irrelevant:

  • That the method is being called from an overload
  • That the method argument is a conditional expression

So if you think about it as:

Double d = getSomeDoubleValueFromAnywhere();
add(d);

... which method would you expect to be called? Presumably the add(Double) method - so that's what is called in your situation too.

The tricky part is working out the type of the conditional expression - is it Double or double? I believe the rules (which are hard to follow, IMO) mean that it's Double, due to the use of a null literal (which is of the null type). If instead you had:

Double dv = null;
add(value == null ? dv : value.doubleValue()); 

... then the conditional expression type would be double, and you'd get a NullPointerException if value were ever null, because it would be trying to unbox the null value.

like image 103
Jon Skeet Avatar answered Sep 21 '22 21:09

Jon Skeet