2013-02-10 54 views
2

我正在经历所述方法在Java重载和我试图在eclipse以下程序的输出,该程序是..关于方法在Java重载

public class OverloadingTest { 

    public static void main(String args[]){ 
     List abc = new ArrayList(); 
     List bcd = new LinkedList(); 

     ConfusingOverloading co = new ConfusingOverloading(); 
     co.hasDuplicates(abc); //should call to ArryList overloaded method 
     co.hasDuplicates(bcd); //should call to LinkedList overloaded method 
    } 


} 

class ConfusingOverloading{ 

    public boolean hasDuplicates (List collection){ 
     System.out.println("overloaded method with Type List "); 
     return true; 
    } 

    public boolean hasDuplicates (ArrayList collection){ 
     System.out.println("overloaded method with Type ArrayList "); 
     return true; 
    } 


    public boolean hasDuplicates (LinkedList collection){ 
     System.out.println("overloaded method with Type LinkedList "); 
     return true; 
    } 

} 

并且输出是..

Output 
overloaded method with Type List 
overloaded method with Type List 

现在在解释中被告知..方法重载在编译时使用静态绑定在Java中解决,所以请告诉我如何通过方法重写来实现相同。

回答

1

abcbcd都是List型的,即使你用subclass .hence结果

里继承像List帮助你编写能够与任何它的工作方法初始化它的子类(的ArrayList或LinkedList的)。 所以,

public ArrayListLinkedListCanCallMe(List lst) 
{ 
//now imagine if this method was called with bcd as parameter 
//still lst would be of type List not LinkedList 
//and if lst were allowed to be of type LinkedList then how could List know any 
//of the methods of LinkedList.Therefore lst would always be of type List NOT LinkedList 
} 

可以代之以

co.hasDuplicates((ArrayList)abc); 
co.hasDuplicates((LinkedList)bcd); 

(ArrayList)abc可以抛出异常投ABC是LinkedList型的。你可以使用instanceof运算符来检查,如果ABC是ArrayList型然后投它..

0

在这种特殊情况下,如果hasDuplicates意味着它说什么,我会hav一种以List为参数的方法。它只是创建一个用列表内容初始化的HashSet,并将其大小与List大小进行比较。

如果您确实需要特殊的例外代码,例如ArrayList可以在List参数方法中使用instanceof。

但是,当您使用接口类型时,找到适用于接口所有实现的常用方法要好得多。如果你不能这样做,你必须允许传递一个实现接口的类的对象的可能性,但不是你有特殊情况代码的类之一。如果您需要java.util.ArrayList的特殊大小写代码,那么为什么您不需要特殊的大小写代码来实现Arrays.asList用作其结果的私有类的实例?

如果问题在您自己的代码中存在不同的类,那么通常可以将问题转向并将该方法置于当前参数类中,以便传统的覆盖工作。