2012-10-28 26 views
0

我曾经使用过此link消失了;但我感到困惑与下面的示例代码: -选择最具体方法 - 整蛊方法重载?

public class NullTest { 

    public static void method(Object obj){ 
    System.out.println("method with param type - Object"); 
    } 

    public static void method(String str){ 
    System.out.println("method with param type - String"); 
    } 

    public static void method(StringBuffer strBuf){ 
    System.out.println("method with param type - StringBuffer"); 
    } 

    public static void main(String [] args){ 
    method(null); //... compile-time error! 
    } 
} 

错误,我得到的是: -

[email protected]:/home/Data/JAVA/practice$ javac trickyMethodOverloading.java 
trickyMethodOverloading.java:16: error: reference to method is ambiguous, both method method(String) in trickyMethodOverloading and method method(StringBuffer) in trickyMethodOverloading match 
    method(null); //... compile-time error! 

任何建议,请

回答

2

你有相同的名称为所有的你的方法。现在Java可以区分它们的唯一方法是通过它们收到的参数来知道要使用哪一个。然而,使用null没有任何东西窄了,所以你的编译器不能完成编译,因为它不知道用哪一个。

1

在方法重载,最具体的方法的这样的情况下,或者换句话说,方法属于最深类中继承树的层次结构选择的在运行时,只要所使用的类属于同一分支中继承树,以便可以毫无歧义地找到一个类。 (从我自己的理解,而不是从java文档:))

然而,在你的例子中,你有2个重载的方法与String和StringBuffer分别不属于继承树中的同一分支。这就是编译器抱怨的原因。 Different branches in Inheritance Same branch in inheritance tree

,如果你有发言权,3类A,B,C,其中B扩展A和C的扩展B.如果您有

public class NullTest{ 

    public static void method(A a){ 
    System.out.println("method with param type - A"); 
    } 

    public static void method(B b){ 
    System.out.println("method with param type - B"); 
    } 

    public static void method(C c){ 
    System.out.println("method with param type - C"); 
    } 


    public static void main(String [] args){ 
    method(null);// compiles successfully and will print- "method with param type - C" 
    } 
} 

这这种情况下,层次结构,这种例子作品因为A,B和C在继承树中属于同一层次。因此编译器只是试图去最深的层次,它可以找到无歧义的单一类(在这种情况下,C)。 另外,如果你从你的代码中删除String或StringBuffer的,它会工作。