【问题标题】:Regarding method overloading in java [duplicate]关于java中的方法重载[重复]
【发布时间】:2013-01-25 20:36:02
【问题描述】:

我正在通过 java 中的方法重载,我正在 eclipse 中尝试以下程序的输出,程序是..

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 中的静态绑定解决的,所以请告知我如何通过方法覆盖来实现相同的目标。

【问题讨论】:

    标签: java


    【解决方案1】:

    abc,bcd 两者都是 List 类型,即使您使用 subclass 初始化它也是如此。因此结果

    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);
    

    但是如果 abc 是 LinkedList 类型,(ArrayList)abc 可以抛出强制转换异常。您可以使用 instanceof 运算符检查 abc 是否是 ArrayList 类型然后强制转换它..

    【讨论】:

      【解决方案2】:

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

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

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

      当问题是您自己代码中的不同类时,您通常可以扭转问题并将方法放在当前的参数类中,这样传统的覆盖就可以工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-27
        • 1970-01-01
        • 2023-03-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多