![](/img/trans.png)
[英]Java Generics: interface method that receives type argument of implementing class
[英]How to write method that has argument implementing an interface in Java
我有一個名為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<T>
。 如果將這些類中的方法簽名更改為public ListInterface<T> join(ListInterface<T> otherList)
,那么我將無法再對DoubleLinkedList
或MyArrayList
使用其他特定方法。 我應該如何在ListInterface
中更改方法簽名以解決此問題?
我應該如何在
ListInterface
中更改方法簽名以解決此問題?
你不知道 ListInterface
的方法簽名是正確的。
如果將這些類中的方法簽名更改為
public ListInterface<T> join(ListInterface<T> otherList)
,那么我將無法再對DoubleLinkedList
或MyArrayList
使用其他特定方法。
那是對的。 您不應該使用任何子類方法,因為otherList
可能與this
列表類型不同。 用戶可能會嘗試將DoubleLinkedList
加入MyArrayList
,是嗎?
僅使用接口方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.