Question

I am having some problem, and I can't understand why it isn't working. I have a Parent class:

public abstract class Parent {
    ...
}

and 2 Child classes:

public class Child1 extends Parent {
    ...
}

public class Child2 extends Parent {
    ...
}

I have a method, which is working with the children list. But it should work with both type Child1 and Child2, so I thought it should work:

public static void doSomething(List<Parent> list) {
    ...
}

and this is how I call it:

List<Child1> children = dao.getChildren("1");
doSomething(children);

List<Child2> children2 = dao.getChildren("2");
doSomething(children2);

But it doesn't work, it shows this error:

The method doSomething(List<Parent>) in the type MyClass is not applicable for the arguments (List<Child1>)
The method doSomething(List<Parent>) in the type MyClass is not applicable for the arguments (List<Child2>)

How could I write this code?

Was it helpful?

Solution

Oh I did it! This code is working for the doSomething method:

public static void doSomething(List<? extends Parent> list) {
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top