Rules for choosing an overloaded method with multiple parameters in Java

I know about overload rules in Java, but for some situations my intuition does not work.

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 that (1, 2 or 3) will compile successfully?

The first and second will be, but the third will not (due to an ambitious method call).

Why is javac designed this way and cannot solve this situation? Why not throw # 3 at # 1?

+4
source share
2 answers

Good question!

You suggest that # 3 should be distinguished to # 1, it seems to make sense, because it has one less boxing box.

This is probably the reason why the Java solution gives you an error instead of choosing the method with the smallest boxing:

  • This situation is rare .
  • Finding out which method to use for automatic boxing can be expensive *.
  • The logic by which to choose a method may be too subjective .
  • Therefore, in this case , Java makes you not to be ambiguous .

* The accepted answer to a question related to Sotirios gives some insight into why this might be too costly to be worth it.

+2
source

The first and second will be, but the third will not (due to an ambiguous method call). Why can't Java solve this situation? Why not throw # 3 at # 1?

As you already mentioned, Long can be auto-updated for a long time. However, there is ambiguity - if only the second long autobox, you will get No. 1. If both of them are autoboxes, you will receive # 2.

Since Java cannot decide which method you had in mind, this causes an error.

0
source

Source: https://habr.com/ru/post/1501879/


All Articles