方法重载时的优先级

简述

在同一个类中,如果多个方法有相同名字、不同参数,即称为重载。在编译器眼中,方法名称+参数类型+参数个数,组成一个唯一键,称为方法签名,JVM通过这个唯一键决定调用哪种方法。(注意方法返回值并非这个组合中的一员)

优先级

有时候通过肉眼就可以辨别出JVM会调用哪个方法,但有时候却容易混淆,如下代码

public class Test {

    public static void test(int i){
        System.out.println("this is test(int i)");
    }

    public static void test(Integer i){
        System.out.println("this is test(Integer i)");
    }

    public static void test(int... i){
        System.out.println("this is test(int... i)");
    }

    public static void test(Object i){
        System.out.println("this is test(Object i)");
    }
}

如果调用test(1)会真正调用哪个方法呢?
下面给出相关的优先级

  1. 精确匹配
    精确匹配是指对于前两个方法,如果调用时传入的是基本数据类型,会执行第一个方法,传入的是包装类型,会执行第二个方法
  2. 如果是基本数据类型,自动转换成更大范围的基本类型
    是指如果将第一个方法的入参改为(long i),此时调用test(1)仍然是执行本方法,它的优先级高于(Integer i)
  3. 自动拆装箱
    这个很好理解,这里不解释了
  4. 通过子类向上转型继承路线依次匹配
    如Integer的父类是Object。这里需要注意null可以匹配任何对象,如test(null)会调用参数为Integer的方法,如果添加一个参数为String的方法就会编译报错了,因为无法确定null应该选择Integer还是String
  5. 通过可变参数匹配
  6. 注意
    以下情况是无法调用test(1, 2)的,你是在挑战编译器忍耐极限!
    public static void test(Integer i, int j){
        System.out.println("1");
    }

    public static void test(int i, Integer j){
        System.out.println("2");
    }

你可能感兴趣的:(方法重载时的优先级)