Constructor not accepting list of derived class as argument [duplicate]

1 week ago 10
ARTICLE AD BOX

I have tried using both base class and interface and in both instances I am told a constructor that takes my arguments does not exist. I have two classes that are related to each other and I want to instantiate a different class with either one. Here's what my set up looks like:

The base class

public class MyClassBase implements MyClassBaseIF { public MyClassBase(){ //stuff } }

The child class

public class MyClassChild extends MyClassBase implements MyClassBaseIF { public MyClassChild() { //stuff } }

The interface

public interface MyClassBaseIF { public void doStuff() { //stuff } }

I want to instantiate a new class that takes a list of either the base class or the child as a constructor argument. I've tried doing it via interface and simply via inheritance, it does not matter to me which to implement as long as one works but I get the same error with both

public class BigImportantClass { public BigImportantClass(List<MyClassBaseIF> stuff) { List<MyClassBaseIF> a = stuff; } }

or

public class BigImportantClass { public BigImportantClass(List<MyClassBase> stuff) { List<MyClassBase> a = stuff; } }

if I create a list of List<MyClassChild> x = functionThatReturnsTheList() no matter which construction option I use for new BigImportantClass(x) I still get

The constructor BigImportantClass(List< MyClassChild >) is undefined

Is my issue rooted in the fact that I'm dealing with a list of base/child/interface or is there something more fundamentally wrong I'm doing?

This is how I ended up implementing a solution

public class BigImportantClass { public BigImportantClass(List<? extends MyClassBaseIF> stuff) { List<MyClassBaseIF> a = new ArrayList<>(); a.addAll(stuff); } }

This lets me still do sorting and adding to a list that I'm doing elsewhere.

Read Entire Article