Reputation: 43
I'm using the .readAll method of the opencsv
library which returns a List<String>
. I thought List
was an interface and therefore cannot be instantiated, so how can it return a List<>
object?
I thought that because ArrayList<>
extends the List
interface, I could do the following by polymorphism:
ArrayList<String[]> transactions = reader.readAll();
Where .readAll()
returns a List<>
object. However, it doesn't work as it expects List<>
not ArrayList<>
.
Why doesn't polymorphism work here, i.e. why can't I assign a List<>
interface return value to the implementing class ArrayList
? And how can an interface be instantiated as the method return value?
Thanks
Upvotes: 2
Views: 295
Reputation: 1422
Interesting question. Its answer is not straightforward.
instance
(interface can’t be instantiated) of an interface but we can make reference of it
that refers to the Object of its implementing class.e.g:
public List getData(){
...
...
ArrayList<String> sArrList = new ArrayList();
...
return sArrList;
}
So, when you return sArrList
, which is an ArrayList but your return type is List. From point 1, list reference points an ArrayList, which on is, its implementation.
Look, ArrayList is a solid implementation of the List interface. There are some solid implementations of List interface like ArrayList, LinkedList... .
So, when we try to assign a List to an ArrayList, Java compiler fails to decide which solid implementation it is actually. Is it an arraylist or linkedlist?
So, you can overcome this situation by typecasting. You confirm java complier that, ok, don't worry, it is an arraylist. you can perform all arraylist operation here without further thinking :)
Upvotes: 1
Reputation: 3418
Polymorphism work in the reverse order of what you understood, means that any object of a parent class/interface (in this case a List
) can hold value of a child class (or a class that implements the interface):
List a = new ArrayList(); //correct
ArrayList b = new List(); //incorrect
so how can it return a List<> object?
You can use interface as a return type. Read this question for clarification.
Upvotes: 2