Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

java - How JVM finds method (parameter with the closest matching) to call in case of function overloading

The JVM decides which overloaded method to call at compile time. I have one example:

public class MainClass{

  public static void go(Long n) {System.out.println("takes Long ");}
  public static void go(Short n) {System.out.println("takes Short ");}
  public static void go(int n) {System.out.println("takes int ");}

  public static void main(String [] args) {
    short y = 6;
    long z = 7;
    go(y);
    go(z);
    go((Short)y);
  }
}

According to my understanding, it should print the following:

takes Short
takes Long
takes Short

... but the actual output is:

takes int
takes Long
takes Short

However if I have the following three functions:

public static void go(Integer n) {System.out.println("takes Integer");}
public static void go(Long n) {System.out.println("takes Long ");}
public static void go(Short n) {System.out.println("takes Short ");}

... and call it using:

int a= 10; and go(i);  //output : takes Integer.

... why there is there a difference for short and int?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

See JLS Section 15.12.2, for rules compiler follows to determine which method to invoke. Compiler always chooses the most specific method in case your methods are overloaded:

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.

Compiler first tries to resolve the method without boxing or unboxing as quoted there:

The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

Emphasis mine.

So, in your 1st code, since short can be used as argument for parameter of type int. Compiler will not use the method with parameter Short, as that requires boxing. While in case of long type, since it cannot be used as argument for type int, it goes for boxing it to Long. Remember Widening is preferred over Boxing.

In your 2nd, there is no other way than boxing int to Integer. So, it calls method with Integer parameter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...