What happens when we pass int arguments to the overloading method having float as a parameter for one method and another having double param

前端 未结 3 553
清歌不尽
清歌不尽 2020-12-01 19:54

In overloading concept, i am having one doubt, that is . when i comes to overload the method with int value the method call\'s the float parameter method rather the double p

相关标签:
3条回答
  • 2020-12-01 20:05

    In Java,there is relation between sub class and super class and also ascending level for primitives from byte short.... to double.

    The rule is, whenever there is ambiguity which overloaded method to choose, the most near one sub class overloaded method or nearest primitive in ascending order is chosen.

    0 讨论(0)
  • 2020-12-01 20:06

    as per http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

    5.1.2. Widening Primitive Conversion

    19 specific conversions on primitive types are called the widening primitive conversions:

    byte to short, int, long, float, or double

    short to int, long, float, or double

    char to int, long, float, or double

    int to long, float, or double

    long to float or double

    float to double

    0 讨论(0)
  • 2020-12-01 20:26

    Testing a variant of your code, except with a byte literal and overloaded methods with various combinations of short, int, and long appears to imply that the compiler chooses the "least widening" conversion if more than one is available.

    Thus:

    • Between a short and an int, if you call the overloaded method with a byte, the short variant will be chosen
    • Between an int and a long, if you call the overloaded method with a byte or short, the int variant will be chosen

    And so forth.

    Thus, because long can be widened to either float or double, and because the float conversion is the "least widening", the float overload is chosen.


    I think this is because of the "choose the most specific overload" way that the compiler resolves multiple possible overloads. From the JLS, section 15.12.2.5:

    The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

    So by this, a method that takes a float is "more specific" than a method that takes a double because any invocation handled by a method that takes a float can always be handled by a method that takes a double, but not the other way around.

    0 讨论(0)
提交回复
热议问题