简体   繁体   English

Java通用集合和继承

[英]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 ? 类型List <capture#3-of?中的方法add(capture#3-of?扩展A)。 extends A> is not applicable for the arguments (B) 扩展A>不适用于参数(B)

the line where the list is instantiated. 实例化列表的行。

How can I get this to work? 我该如何工作?

Can you just type AbsClass ? 您可以输入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 ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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