简体   繁体   English

包含扩展类的抽象类列表

[英]List of abstract class containing extended classes

So my problem is this. 所以我的问题是这个。 I am using java and I am trying to do something like this (I am working offline so it is harder for me to give code examples but if needed I will) : 我正在使用Java,并且正在尝试执行以下操作(我正在离线工作,因此我很难给出代码示例,但如果需要的话,我会这样做):

Class A - abstract class
Class B - abstract class with list<A> as property
Class C - extends class A
Class D - extends class B

and in this class, in the constructor I am trying to create the list which is in the B properties with a new object from class C. 在这个类的构造函数中,我试图用C类的新对象创建B属性中的列表。

The error is:  Type mismatch: cannot convert from C to A.

I can't seem to make it work. 我似乎无法使其工作。 Any ideas why? 有什么想法吗?

Edit: 编辑:

abstract public class A {
   public int theInt;
}

abstract public class B {
   public List<A> theList;
}

abstract public class C extends A {
}

abstract public class D extends B {
   public D(){
       this.theList = new ArrayList<C>();
   }
}

This is the code and I have a compiliation error like I mentioned. 这是代码,我有一个提到的编译错误。

Initialize it as 初始化为

List<A> list= new ArrayList<A>();

That way you would be able to add any subtype of A 这样,您就可以添加A的任何子类型


If you want to assign ArrayList<C> to as it appears from the comment 如果要分配ArrayList<C>到注释中显示的位置

Do it this way 这样做

list.AddAll(arrayListC);

ArrayList<C> does not extend List<A> . ArrayList<C>不扩展List<A> Therefore the assignment 因此作业

this.theList = new ArrayList<C>();

is invalid. 是无效的。

You can fix this by adding a type parameter to B 您可以通过向B添加类型参数来解决此问题

abstract public class B<T extends A> {
   public List<T> theList
}

abstract public class D extends B<C> {
   public D(){
       this.theList = new ArrayList<C>();
   }
}

You could even add a type parameter to D : 您甚至可以向D添加类型参数:

abstract public class D<T extends A> extends B<T> {
   public D(){
       this.theList = new ArrayList<T>();
   }
}

Alternative: 选择:

Just use ArrayList<A> instead of ArrayList<C> . 只需使用ArrayList<A>而不是ArrayList<C>


Please note that lst.add(x); 请注意, lst.add(x); will not compile for the following type combinations: 不会针对以下类型组合进行编译:

    type of lst             |     type of x
============================|================================
  List<? extends A>         |  A
----------------------------|--------------------------------
  List<C>                   |  E extends A but not C
----------------------------|--------------------------------
  List<? extends A>         |  E extends A

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

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