带装箱/合并的Java方法重载 [英] Java Method Overloading with Boxing/Widening
问题描述
我正在Java Se 7 OCA上工作,无法弄清为什么以下代码无法编译. main方法中的aMethod调用给出了编译错误,指出了模棱两可的方法.在此重载方法示例中,加宽和装箱之间的优先顺序规则似乎冲突.
I am working on Java Se 7 OCA and could not figure out why below code does not compile. aMethod call in main method gives compile error stating ambiguous method. Precedence rules between widening and boxing seems to clash in this overloading method sample.
public class Overloading {
public static void main(String[] args) {
Byte i = 5;
byte k = 5;
aMethod(i, k);
}
static void aMethod(byte i, Byte k) {
System.out.println("Inside 1");
}
static void aMethod(byte i, int k) {
System.out.println("Inside 2");
}
static void aMethod(Byte i, Byte k) {
System.out.println("Inside 3 ");
}
}
错误是"方法aMethod(byte,Byte)对于重载类型不明确". 当我注释掉第一种方法时,对于第二种方法也会给出相同的错误.
The error is "The method aMethod(byte, Byte) is ambiguous for the type Overloading". when I comment out first method, it gives same error for second method.
我的想法是: 第一种方法需要拆箱和装箱 第二种方法需要拆箱和拓宽 第三种方法只需要装箱. 因此,它必须是第三种方法,因为它需要最少的转换,并且所有人都具有装箱转换.
My thinking is: First method needs unboxing and boxing Second method needs unboxing and widening Third method needs only boxing. So it must be third method, since it needs the least conversion and all of them have boxing conversion.
推荐答案
问题在于所有这些方法:
The problem is with all these methods:
static void aMethod(byte i, Byte k) {
System.out.println("Inside 1");
}
static void aMethod(byte i, int k) {
System.out.println("Inside 2");
}
static void aMethod(Byte i, Byte k) {
System.out.println("Inside 3 ");
}
Java不知道它应该在行中调用哪一个:
Java doesn't know, which one it should invoke in line:
aMethod(i, k);
根据 i
可以是unboxed
至byte
(5.1.8),也可以保留为Byte
(5.1.1)-> 2个变体
i
could be unboxed
to byte
(5.1.8) or leaved as Byte
(5.1.1) -> 2 variants
k
可以是boxed
到Byte
(5.1.7),也可以扩展到int
类型(5.1.2)-> 2个变体.
k
could be boxed
into Byte
(5.1.7) or widened to int
type (5.1.2) -> 2 variants.
这篇关于带装箱/合并的Java方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!