2

Inheritance in Java. Is it possible to do like this:

List<ParentEntity> loc = Locations, 

where Locations is List<ChildEntity>

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Sergey
  • 7,933
  • 16
  • 49
  • 77

2 Answers2

5

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 1
    And he wont be able to add anything else than `null` to his list – Jerome Nov 23 '12 at 15:50
  • Sorry, I had to reassign the answered mark to Jerome. His solution really helped me. I've just test it. Anyways thank you very much! – Sergey Nov 23 '12 at 16:18
  • @Sergey.. Ah! common. It's absolutely all right. You never have to feel sorry for changing your accepted answer. Accept the most suited answer, wihout 2nd thought. :) – Rohit Jain Nov 23 '12 at 16:19
  • Thank you! :) In any case this answer helped me as well – Sergey Nov 23 '12 at 17:02
  • @Downvoter.. Any particular reason for downvote that you think I deserve to know? – Rohit Jain Nov 23 '12 at 21:09
4

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.

Jerome
  • 2,104
  • 1
  • 17
  • 31