0

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.

2
  • The same applies to C# - you may want to check out stackoverflow.com/questions/2033912/… as it has very clear example why it is a problem. The variance concept is tricky, so read all the linked answers from duplicate suggested by @Progman, my link is just another way to explain it that worked for me - it is impossible to know in advance which one clicks. Commented Nov 25 at 19:15
  • Thank you @Progman what you linked sent me down a good path. I'll add my solution and close out Commented Nov 25 at 19:20

1 Answer 1

1

This ended up solving all my issues

public class BigImportantClass {
    public BigImportantClass(List<? extends MyClassBaseIF> stuff) {
        List<MyClassBaseIF> a = new ArrayList<>();
        a.addAll(stuff);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.