该方法对于 Error 类型不明确 [英] The method is ambiguous for the type Error

查看:53
本文介绍了该方法对于 Error 类型不明确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解 JAVA 中的重载是如何工作的,并试图掌握在 JAVA 中加宽、自动装箱和可变参数时应用的各种重载规则.我无法理解以下场景中发生的情况:

I am trying to understand how Overloading in JAVA works and trying to get grasp of various overloading rules that are applied in case of widening, autoboxing and varargs in JAVA. I am not able to understand what is happening in the following scenario:

 package package1;

 public class JustAClass {
     public static void add(int a, long b) {
         System.out.println("all primitives");
     }

   //public static void add(Integer a, long b) {
   //     System.out.println("Wraper int, primitive long");
   //}

     public static void add(int a, Long b) {
         System.out.println("Primitive int, Wrapper long");
     }

     public static void add(Integer a, Long b){
         System.out.println("All wrapper");
     }

     public static void main(String[] args) {
        int a = 10;
        Integer b = 10;
        long c = 9;
        Long d = 9l;

        add(a,c);
        add(a,d);
        add(b,c);
        add(b,d);
 }

}

此时,我在第三次调用 add 方法时遇到编译错误,提示 该方法对于 Error 类型不明确.为什么会这样?确定哪种方法调用有效的规则是什么?在以下情况下究竟发生了什么?我觉得 fourth 重载的 add 方法应该可以工作.请帮助我理解这背后的概念.

At this point, I get a compilation error at the third invocation of the add method saying The method is ambiguous for the type Error . Why is this so? What are the rules for determining which invocation of method will work? What is exactly happening in the following case? I feel that fourth overloaded add method should work. Please help me understand the concept behind this.

推荐答案

方法重载解析有 3 个阶段.第一阶段不进行自动装箱/拆箱,这意味着需要对传递的参数进行装箱/拆箱以匹配 add 的重载版本之一的方法只有在不匹配时才会被考虑发现不需要装箱/拆箱.这就是为什么您的 3 个具有单个完全匹配项的调用有效的原因.关于add(b,c);,请看下面为什么不明确.

There are 3 stages to method overloading resolution. The first stage doesn't do auto-boxing/unboxing, which means methods that require boxing/unboxing of the passed parameters in order to match one of the overloaded versions of add will only be considered if no match was found that doesn't require boxing/unboxing. That's why 3 of your calls, which have a single exact match, work. Regarding add(b,c);, see below why it's ambiguous.

   add(a,c); // exact match to add(int a, long b)
   add(a,d); // exact match to add(int a, Long b)
   add(b,c); // there is no exact match, so at least one of the passed parameters must
             // be boxed or unboxed. However, by unboxing b to int or boxing 
             // c to Long, each of the three add methods can match, and the 
             // compiler doesn't know which one to prefer
   add(b,d); // exact match to add(Integer a, Long b)

这篇关于该方法对于 Error 类型不明确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆