【问题标题】:How to write method that has argument implementing an interface in Java如何编写具有在 Java 中实现接口的参数的方法
【发布时间】:2018-10-09 20:41:26
【问题描述】:

我有一个名为ListInterface<T> 的接口,它具有join 方法:

public interface ListInterface<T> {
     /**
     * Join a new list to the original list.
     * @param otherList The new list to be joined.
     * @return Original list with appended part from the new list.   
     * @throws IllegalArgumentException.
     */
     public ListInterface<T> join(ListInterface<T> otherList) throws IllegalArgumentException;
}

DoubleLinkedList 和 MyArrayList 两个类实现了这个接口。 所以在DoubleLinkedList,我需要这样写join:

public ListInterface<T> join(DoubleLinkedList<T> otherList) throws IllegalArgumentException {
    (...)
}

在MyArrayList:

public ListInterface<T> join(MyArrayList<T> otherList) throws IllegalArgumentException {
    (...)
}

但这是不可能的,参数的类型必须是ListInterface&lt;T&gt;。如果我将这些类中的方法签名更改为public ListInterface&lt;T&gt; join(ListInterface&lt;T&gt; otherList),那么我将无法再在DoubleLinkedList 或MyArrayList 上使用其他特定方法。我应该如何更改 ListInterface 中的方法签名以解决此问题?

【问题讨论】:

    标签: java class generics methods interface


    【解决方案1】:

    我应该如何更改ListInterface 中的方法签名以解决此问题?

    你没有。 ListInterface 的方法签名是正确的。

    如果我将这些类中的方法签名更改为public ListInterface&lt;T&gt; join(ListInterface&lt;T&gt; otherList),那么我将无法再在DoubleLinkedList 或MyArrayList 上使用其他特定方法。

    没错。您不应该使用任何子类方法,因为otherList 可能与this 的列表类型不同。用户可能会尝试将DoubleLinkedList 加入MyArrayList,是吗?

    只使用接口方法。

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      相关资源
      最近更新 更多