簡體   English   中英

如何編寫帶有參數的方法來實現Java接口

[英]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;
}

兩個類DoubleLinkedListMyArrayList實現此接口。 所以在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) ,那么我將無法再對DoubleLinkedListMyArrayList使用其他特定方法。 我應該如何在ListInterface中更改方法簽名以解決此問題?

我應該如何在ListInterface中更改方法簽名以解決此問題?

你不知道 ListInterface的方法簽名是正確的。

如果將這些類中的方法簽名更改為public ListInterface<T> join(ListInterface<T> otherList) ,那么我將無法再對DoubleLinkedListMyArrayList使用其他特定方法。

那是對的。 您不應該使用任何子類方法,因為otherList可能與this列表類型不同。 用戶可能會嘗試將DoubleLinkedList加入MyArrayList ,是嗎?

僅使用接口方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM