简体   繁体   中英

Java generic collections and inheritance

Basically I need to have an abstract class, that contains a field of a list that details it can hold subclasses of a certain class, and then create a concrete class that stores a specific subclass of that certain class.

Better explained in code I am sure:

public class A {
}

public class B extends A {
}

public abstract class AbsClass {
    protected List<? extends A> list;
}

public class ConClass extends AbsClass {
    list = new ArrayList<B>();
}

With the above code i get the compiler error

The method add(capture#3-of ? extends A) in the type List < capture#3-of ? extends A> is not applicable for the arguments (B)

the line where the list is instantiated.

How can I get this to work?

Can you just type AbsClass ?

public abstract class AbsClass<T extends A> {
    protected List<T> list;
}

public class ConClass extends AbsClass<B> {
    list = new ArrayList<B>();
}

Of course at that point it's not necessary to even move the instantiation to the subclass:

public abstract class AbsClass<T extends A> {
    protected List<T> list = new ArrayList<T>();
}

public class ConClass extends AbsClass<B> {
    //... other stuff ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM