0

Imagine that I have a Parent abstract class

public abstract class ParentAbstract {}

And one Child

public abstract class ChildA extends ParentAbstract {}

If I have a method that returns a list of ChildA that looks like this:

private List<ChildA> results() {
  return new ArrayList<ChildA>();
}

Why can't I use this method like so? Which calls the above results method

private List<Parent<?>> absctractResults() {
  return results();
}

The compiler will throw

java: incompatible types: List<ChildA> cannot be converted to List<Parent<?>>

Why can't the compiler allow that and how to make a method that returns a list of the abstract class that calls other methods returning the child classes?

  • Why did you putted `>` at `IncomingMessageAbstract`? You parent has no generic. – KunLun Oct 05 '21 at 11:33
  • As soon as you give a `List` one cannot turn it into a `List` as putting an ParentAbstract in the list, would corrupt others holding a `List` - they think. Hence not allowed. – Joop Eggen Oct 05 '21 at 11:34
  • You can do this kind of cast `return (List)(List>)results();`, but I'm not sure that is a good idea. – KunLun Oct 05 '21 at 11:42
  • @KunLun You're right, I can totally remove that – Thomas Pierre Oct 05 '21 at 11:48
  • I found a way to convert the list from the results() method : `new ArrayList<>(results.getResults())` is allowed to return a `List` Thanks for your help! – Thomas Pierre Oct 05 '21 at 12:27

0 Answers0