Java overloading - long and float

GauravJ :

I was trying to understand java overloading rules. Everything seems fine except following,

public static void main(String[] args) {
    long aLong = 123L;        
    foo(aLong);
}

private static void foo(double aDouble) {
    System.out.println("Foo aDouble");
}

private static void foo(Long aWrapperLong) {
    System.out.println("Foo Wrapper Long");
}

private static void foo(int anInt) {
    System.out.println("Foo Int");
}

private static void foo(float aFloat) {
    System.out.println("Foo Float");
}

Why does the call resolve to foo(float aFloat). I understand the following from JLS,

This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable There may be more than one such method, in which case the most specific one is chosen.

I have intentionally used Wrapper Long here and not primitive long. Primitive long being 64 bit in size does not end up in foo(double aDouble) but 32 bit float foo(float aFloat).

The question Why does Java implicitly (without cast) convert a `long` to a `float`? further clarifies the answer to this question.

user207421 :

This is because of the 'most-specific' rule in JLS #15, which in turn refers to JLS #4.10, which in turn refers to #4.10.1, which states:

The following rules define the direct supertype relation among the primitive types:

  • double >1 float

  • float >1 long

  • long >1 int

  • int >1 char

  • int >1 short

  • short >1 byte

where "S >1 T" means "T is a direct subtype of S", as per JLS #4.10 immediately above this section.

So in this case, in the absence of a direct match on long, and before looking at auto-boxing, the compiler chooses the nearest available supertype, which is float, by the rules above.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=429245&siteId=1