2

Lets say I've got two classes Person and Child. Child inherits from Person. I have also 2 other classes Class1 and Class2.

Class1 has constructor with only one parameter - its a java.util.List of Person. Class2 has List of Child. I want to pass these childs to Class1 constructor. But I can't do it - Eclipse says that

The constructor Class1(List<Child>) is undefined.

I thought it would be possible because Child inherits from Person. What is the problem?

SSCCE (not compilable) may looks like this:

Somewhere in Class2

List<Child> childs = new ArrayList<Child>();
new Class1(childs);

Class1 constructor

public Class1(List<Person> persons)
{
//do nothing();
}
1
  • 4
    List<Child> is not a sub class of List<Person> Commented Dec 24, 2013 at 13:42

2 Answers 2

4

If a List<Apple> was a List<Fruit>, you could do the following:

List<Apple> apples = new ArrayList<>();
List<Fruit> fruits = apples; // this doesn't actually compile
fruits.add(new Banana()); 

And it would thus completely break the type-safety of generic types. If you want Class1 to accept a list of any type of Person, it should take a List<? extends Person> as argument.

Sign up to request clarification or add additional context in comments.

1 Comment

better answer because there is an explanation why this is impossible
2

If you define a constructor this way

public Class1(List<? extends Person> persons) {
}

you will be able to pass List<Child> to it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.