使用基元及其包装器重载的方法 [英] Method overloading with primitives and their wrappers
问题描述
我正在尝试制定以下方案中使用的规则。请解释为什么我得到2个不同的输出。
I am trying to formulate the rules that are being used in the scenarios below. Please explain why I am getting 2 different outputs.
场景1输出:我是一个对象。
class Test {
public static void main (String[] args) {
Test t = new Test();
byte b_var = 10;
t.do_the_test(b_var);
}
public void do_the_test(Character c) {
System.out.println("I am a character.");
}
public void do_the_test(Integer i) {
System.out.println("I am an integer.");
}
public void do_the_test(Object obj) {
System.out.println("I am an object.");
}
}
场景2输出:我是一个整数。
class Test {
public static void main (String[] args) {
Test t = new Test();
byte b_var = 10;
t.do_the_test(b_var);
}
public void do_the_test(char c) {
System.out.println("I am a character.");
}
public void do_the_test(int i) {
System.out.println("I am an integer.");
}
public void do_the_test(Object obj) {
System.out.println("I am an object.");
}
}
推荐答案
Java语言规范说明了方法签名分辨率:
The Java Language Specification says this about method signature resolution:
第一阶段(§15.12.2.2)执行重载解析而不允许装箱或拆箱转换,或使用变量arity方法调用。如果在此阶段没有找到适用的方法,则处理继续到第二阶段。
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.
在第二种情况下,方法签名涉及 int
适用于没有自动装箱,但扩展数字转换。在第一种情况下,需要扩大转换和自动装箱才能达到整数
签名;但是,Java 要么自动装箱或原始转换,而不是两者。
In your second case, the method signature involving int
is applicable without autoboxing, but with a widening numeric conversion. In the first case, both the widening conversion and autoboxing would be needed to reach the Integer
signature; however, Java does either autoboxing or primitive conversion, never both.
这篇关于使用基元及其包装器重载的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!