java - 为什么 Short 方法调用整数方法?

标签 java overload-resolution

public class Yikes {
    public static void go(Long n) {
        System.out.print("Long ");
    }

    public static void go(Short n) {
        System.out.print("Short ");
    }

    public static void go(int n) {
        System.out.print("int ");
    }

    public static void main(String[] args) {
        short y = 6;
        long z = 7;
        go(y);
        go(z);
    }
}

这个程序给出了输出

int Long

我以为输出是

short Long

这是什么原因?

最佳答案

overload resolution section in the JLS解释原因:

  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.

This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.

  1. 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.

在第一阶段,编译器在其解析中不包含方法go(Short n)。相反,它认为 go(int n) 是一种适用的方法。此方法适用,因为 short 正在加宽转换为 int

关于java - 为什么 Short 方法调用整数方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32569884/

相关文章:

c++ - 具有多个模板继承的模板实例化

java - 带有部分的 ListView 中的 Itemclick 事件

c++ - 检测习语与默认参数类型匹配

java - 寻找实现 javac 重载解析算法的 Java 代码

C++ 重载解析、用户定义转换和函数模板

c++ - std::optional:不参与重载决议与被定义为已删除

java - 如何为简单的学校应用程序设计对象

java - Hibernate SaveOrUpdate - 多个工作线程

Java:如何在 JVM 加载类时拦截它们

java - 如何调整JLabel ImageIcon的大小?