[英]Method Overloading for Null Argument by passing 0 and null
I have seen questions on Stack Overflow about a method overloading for null argument but didn't solve my confusion and I tried something different which was not discussed in there answers that's why asking this question. 我在Stack Overflow上看到过有关为null参数重载方法的问题,但并没有解决我的困惑,因此我尝试了一些其他未解决的问题,这就是为什么要问这个问题。
I want the reason when I pass "null" it executes the function whose argument type is double and when I pass "0" or any other numeric digit like 1,2,10 etc to the function it executes the function whose argument type is "Object". 我想知道为什么当我传递“ null”时它执行参数类型为double的函数,而当我传递“ 0”或任何其他数字如1,2,10等到函数时,它执行参数类型为“宾语”。 I know there is a difference in NULL and 0 here is the difference.
我知道NULL有区别, 这里有0。
Thanks! 谢谢!
Code: 码:
public class NullArgumentOverloading {
public static void main(String[] args) {
NullArgumentOverloading obj = new NullArgumentOverloading();
obj.overLoad(null); // prints "Double array argument method."
obj.overLoad(0); // prints "Object o argument method."
}
private void overLoad(Object o) {
System.out.println("Object o argument method.");
}
private void overLoad(double[] dArray) {
System.out.println("Double array argument method.");
}
}
Java will always try to use the most specific version of a method that's available (see JLS 15.12.2 ). Java将始终尝试使用可用方法的最特定版本(请参见JLS 15.12.2 )。
Object
, double[]
can both take null as a valid value. Object
, double[]
都可以将null作为有效值。 Therefore both are suitable. 因此,两者都是合适的。
Object
is the super-type of double[]
and therefore more specific than just Object
. Object
是double[]
的超类型,因此比Object
更具体。 So thats the reason why it prints "Double array argument method." 因此,这就是它显示“双数组参数方法”的原因。 when you pass
null
to the function 当您将
null
传递给函数时
For the ohter Question: As already explained in the comments, when you pass 0
which is a primitive int
, will be boxed automatically into an Integer
which have Object
as super-type, so it prints "Object o argument method." 对于其他问题:正如注释中已经解释的那样,当您传递
0
,它是一个原始int
,它将被自动装箱到具有Object
作为超类型的Integer
中,因此它会打印“ Object o参数方法”。
You can find more info in Method Overloading for null argument 您可以在“ 方法重载”中找到有关null参数的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.