Search code examples
javalistarraylistsubclasssuperclass

List<A> referring to a List<subclass-of-A>


If I have a Class A that contain a List of children with class A like

public Class A
{
    protected List<A> children = new ArrayList<A>();
    ...
}

Is it then possible in a subclass B to have its own children of another class C and create a reference to the children list in class A? Class A has methods that the other classes want to use, e.g. send their children to. However, the class A is the general class, and B and C are more specific. So to make the reading of the code easier and to avoid a lot of typecasting I would like the List of the super class to refer to the List of the subclasses.

So when I update otherChildren, the children list will also be updated. I'd like to do something like in the example below, but does that not work and it can't be casted either (children = (List< A >) otherChildren).

But is there anyway to achieve this? I'd really like to avoid all the typecasting I'll get otherwise.

public Class B extends A
{
    private List<C> otherChildren = new ArrayList<C>();

    public B()
    {
        children = otherChildren;
        ...
        // Modification of otherChildren will result in the same
        // modification in children
    }
}

public Class C extends A
{
     ...
}

Solution

  • All you have to do is change the declaration of children in class A to :

    protected List<? extends A> children = new ArrayList<A>();