简体   繁体   中英

I can't call a method from a class that extends my List interface

I have a List interface as well as a SLList class that implements List. I have another class, ListIterator, that uses the SLList to instantiate an object like this:

List<E> list = new SLList<>();

That part is fine. However, when I try to call a method that is only found in the SLList class, I get a compiler error saying that it can't find the method.

If you want to call a method from SLList, the declaration of the variable needs to be of the SLList type:

SLList<E> list = new SLList<>(); //this is what I mean

For the compiler only the declared type matters (the part on the left)

So you are trying to do something like this?

List<E> list = new SLList<>();
list.someMethodOnlyInSLList();

Well, in the second line the compiler knows only that list is a List<E> so you can't call any method present in the implementation, that isn't part of the interface.

I you want to do that you have either

  • create a new interface, possibly extending from List which contains that method and use that interface instead of List

  • Use SLList<E> list = new SLList<>(); instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM