2

I have an interface called ListInterface<T> that has the method 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;
}

Two classes DoubleLinkedList and MyArrayList implement this interface. So in DoubleLinkedList, I need to write join like this:

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

And in MyArrayList:

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

But this is not possible and the type of arguments must be ListInterface<T>. If I change the method signatures in these classes to public ListInterface<T> join(ListInterface<T> otherList), then I can't use other specific methods on DoubleLinkedList or MyArrayList anymore. How should I change the method signature in ListInterface in order to fix this?

1 Answer 1

4

How should I change the method signature in ListInterface in order to fix this?

You don't. ListInterface's method signature is correct as is.

If I change the method signatures in these classes to public ListInterface<T> join(ListInterface<T> otherList), then I can't use other specific methods on DoubleLinkedList or MyArrayList anymore.

That is correct. You should not be using any subclass methods because otherList may not be the same type of list as this. The user might try to join a DoubleLinkedList to a MyArrayList, yes?

Use the interface methods only.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.