Passing an ArrayList of subclass to a constructor that takes ArrayList of superclass?

Viewed 3665

Okay so I'm working on this project for the university and I think I'm doing something wrong here, guess I haven't understood java subclassing and class inheritance enough.

I have rewrote my problem in this little form.

    class SuperClass {

        int dunno;

        public SuperClass(int dunno) {
            this.dunno = dunno;
        }
    }

    class SubClass extends SuperClass {

        int duncare;

        public SubClass(int dunno, int duncare) {
            super(dunno);
            this.duncare = duncare;
        }
    }

    class VeryBigClass {

        ArrayList<SuperClass> superList;

        public VeryBigClass(ArrayList<SuperClass> superList) {
            this.superList = superList;
        }
    }

    public void main(String[] args) {

        new VeryBigClass(new ArrayList<SubClass>()); // this is the problematic line

    }

}

In little words I wrote a lot of classes that extend one more general class, and in many places I have made operations with the superclass (the general one), instead of treating each of the subclasses one by one in the same way.

But I can not create the instance of the class I need, since the constructor takes as argument the superclass. I don't even know how to cast it since new VeryBigClass(new (ArrayList<SuperClass>)ArrayList<SubClass>()); is obviously wrong. Plus, the construction of these instances will be handled by a json library at some point so I'd rather not do such fancy stuff...

3 Answers
Related