在Java中,为什么方法参数中的Object类对象不能接受null

时间:2014-11-30 08:52:22

标签: java

请解释为什么我得到"方法与字符串参数"在输出中。 当我从显示(测试x)方法中删除注释时,它表示"显示参考不明确"。

class Test 
{    
    int a;
    int b;
}

public class TestIt 
{    
    public static void display(String x)
    {
       System.out.println("Method with String param");
    }

    public static void display(Object x)
    {
       System.out.println("Method with Object param");
    }
/*    
    public static void display(Test x)
    {
        System.out.println("Method with Test param");
    }
*/    
    public static void main(String args[])
    {
        display(null);        
    } 

}

2 个答案:

答案 0 :(得分:1)

因为nullObjectString的有效值。你可以施展,

display((String) null);  

将输出

Method with String param

display((Object) null);  

Method with Object param

答案 1 :(得分:1)

因为在确定要调用哪个方法时,编译器会选择匹配参数的最具体的方法。 display(String)display(Object)都匹配对display(null)的调用,但display(String) 更具体而不是display(Object),因此编译器会使用。但是,当您取消注释display(Test)版本时,编译器无法做出选择,因为display(String)display(Test)同样具体。

有关所有血腥的详细信息,请参阅§15.12 of the JLS

相关问题