Inheritance in Java. Is it possible to do like this:
List<ParentEntity> loc = Locations,
where Locations
is List<ChildEntity>
Inheritance in Java. Is it possible to do like this:
List<ParentEntity> loc = Locations,
where Locations
is List<ChildEntity>
No you can't do that. Polymorphism is not allowed in generics.
However you can do: -
List<? extends ParentEntity> loc = new ArrayList<ChildEntity>();
Oh yes, you won't be able to add any new item to your list after that assignment, except null
. That's a restriction you have to bear with.
So, you can first create your ArrayList<ChildEntity>
, fill it, and then assign it to the LHS
.
As @Rohit Jain said, his answer is limited.
You can have a workaround like this :
List<ParentEntity> loc = new ArrayList<ParentEntity>()
loc.addAll(locations);
This time, the limitation is that you lose the initial type of List implementation. And, more importantly, any modification to loc won't be seen on locations.