Method overload resolution in java

后端 未结 5 1119
感情败类
感情败类 2020-11-27 05:45

Here is what I know about overload resolution in java:


The process of compiler trying to resolve the method call from given overloaded method

5条回答
  •  星月不相逢
    2020-11-27 06:21

    In Java, resolving methods in case of method overloading is done with the following precedence:

    1. Widening
    2. Auto-boxing
    3. Var-args

    The java compiler thinks that widening a primitive parameter is more desirable than performing an auto-boxing operation.

    In other words, as auto-boxing was introduced in Java 5, the compiler chooses the older style(widening) before it chooses the newer style(auto-boxing), keeping existing code more robust. Same is with var-args.

    In your 1st code snippet, widening of reference variable occurs i.e, Integer to Object rather than un-boxing i.e, Integer to int. And in your 2nd snippet, widening cannot happen from Integer to String so unboxing happens.

    Consider the below program which proves all the above statements:

    class MethodOverloading {
    
        static void go(Long x) {
            System.out.print("Long ");
        }
    
        static void go(double x) {
            System.out.print("double ");
        }
    
        static void go(Double x) {
            System.out.print("Double ");
        }
    
        static void go(int x, int y) {
            System.out.print("int,int ");
        }
    
        static void go(byte... x) {
            System.out.print("byte... ");
        }
    
        static void go(Long x, Long y) {
            System.out.print("Long,Long ");
        }
    
        static void go(long... x) {
            System.out.print("long... ");
        }
    
        public static void main(String[] args) {
            byte b = 5;
            short s = 5;
            long l = 5;
            float f = 5.0f;
            // widening beats autoboxing
            go(b);
            go(s);
            go(l);
            go(f);
            // widening beats var-args
            go(b, b);
            // auto-boxing beats var-args
            go(l, l);
        }
    }
    

    The output is:

    double double double double int,int Long,Long

    Just for reference, here is my blog on method overloading in Java.

    P.S: My answer is a modified version of an example given in SCJP.

提交回复
热议问题