java - 不明确的重载方法调用已解决

标签 java overloading

当我调用时,call('a'); 它输出“char”,这很好,因为 char 基本类型优先于将其装箱为 Character。

static void call(char i){
    System.out.println("char");
}

static void call(Character i){
    System.out.println("Character");
}

调用 call('a', 'a'); 是如何产生歧义的?

static void call(char i, Character j){
    System.out.println("char");
}

static void call(Character i, Character j){
    System.out.println("Character");
}

我在想的是,对于第二个参数,编译器必须进行装箱,对于第一个参数,完美匹配是 char 原始类型,因此调用 call('a','a'); 可以解析为 call(char i, Character j) 方法。

显然我理解错了,请大神解释一下。

某些解释特定此类示例的链接会有所帮助。

最佳答案

How is call to call('a', 'a'); is ambiguous?

因为为了使 (char i, Character j) 重载适用,围绕装箱的规则开始发挥作用 - 在这一点上 both 调用适用的。这是确定方法签名的第二阶段 (JLS 15.12.2) :

  1. The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

  2. The second phase (§15.12.2.3) performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.

因此在第 2 阶段,两种方法都适用,但确定最具体方法 (JLS 15.12.2.5) 的规则不会使任何一种调用比彼此更具体。这不是“未装箱比装箱更具体”的问题 - 这是“我可以不用任何装箱解决这个问题”之前“我可以用装箱解决这个问题”的问题。

关于java - 不明确的重载方法调用已解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37099156/

相关文章:

java - 父类(super class)和子类参数

c++ - 运算符重载 "+"和 "="问题 -- school asst

struct - 如何重载 'new' 方法?

java - NetBeans IDE 自动完成 'contains'

java - Espresso : returning to application

java - 从 yyyy-MM-dd hh :mm:ss to MM-dd-yyyy hh:mm:ss 转换 java.sql.timestamp

c# - 关于int和double重载的问题

java - 如何创建一个正则表达式,仅用两个替换两个或多个连续的相同字符?

java - 尝试使用 Collections.sort 对我的数组进行排序,但没有成功

c++ - (函数)模板的 C++ 非类型参数是否有序?