Question

I know about overloading rules in Java, but for some situations my intuition doesn't work.

Let's consider an example:

public class Overloading {
    public static void main(String[] args) {
        long primitive = 3;
        Long boxed = Long.valueOf(5);
        doWork(primitive, boxed);     //1
        doWork(boxed, boxed);         //2
        doWork(primitive, primitive); //3                
    }

    static void doWork(Long a, Long b) {}

    static void doWork(long a, Long b) {} 
}

Do you know what (1, 2 or 3) will be compiled successfully?

The first and the second will, but third won't (due to ambitious method call).

Why is javac designed this way and can't resolve this situation? Why not to cast #3 to #1?

Was it helpful?

Solution

Good Question!

You're suggestion that #3 should be cast to #1 does seem to make sense, because it has one less auto-boxing to do.

This is probably the reasoning behind Java's decision to give you an error instead of picking the method with the least boxing involved:

  1. This situation is rare.
  2. Figuring out which method to use for auto-boxing could be expensive*.
  3. The logic behind which method to choose could be too subjective.
  4. Therefore, in this case, Java forces you to not be ambiguous.

*The accepted answer to the question linked to by Sotirios gives some insight into why it might by too expensive to be worth it.

OTHER TIPS

The first and the second will, but third won't (due to ambidous method call). Why java can't resolve this situation? Why not to cast #3 to #1?

As you mentioned, long can be autoboxed to Long. However, there is an ambiguity here - if only the second long is autoboxed, you'd get #1. If both of them are autoboxed, you'd get #2.

Since Java cannot decide which method you meant, it raises an error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top