如何编写具有参数的方法在Java中实现接口
我有一个名为如何编写具有参数的方法在Java中实现接口,java,class,generics,methods,interface,Java,Class,Generics,Methods,Interface,我有一个名为ListInterface的接口,它具有方法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.
ListInterface
的接口,它具有方法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;
}
而在MyArrayList中:
public ListInterface<T> join(MyArrayList<T> otherList) throws IllegalArgumentException {
(...)
}
公共列表接口联接(MyArrayList otherList)引发IllegalArgumentException{
(...)
}
但这是不可能的,参数的类型必须是ListInterface
。如果我将这些类中的方法签名更改为公共ListInterface join(ListInterface otherList)
,则我无法再在DoubleLinkedList
或MyArrayList
上使用其他特定方法。我应该如何更改ListInterface
中的方法签名以修复此问题
我应该如何更改ListInterface
中的方法签名以修复此问题
你没有ListInterface
的方法签名是正确的
如果我将这些类中的方法签名更改为公共ListInterface join(ListInterface otherList)
,则我无法再在DoubleLinkedList
或MyArrayList
上使用其他特定方法
这是正确的。您不应该使用任何子类方法,因为otherList
的列表类型可能与this
的列表类型不同。用户可能尝试将双链接列表
加入到MyArrayList
,是吗
仅使用接口方法
public ListInterface<T> join(MyArrayList<T> otherList) throws IllegalArgumentException {
(...)
}