继承超类的ArrayList属性,但在子类中为其分配不同的类型 [英] Inheriting ArrayList property from superclass but assigning different types to it in child classes
问题描述
我有一个超类A,它有一个受保护的 ArrayList< Object> contentList
。我有从A继承的类B和C.
每个B和C在其构造函数中使用不同类型的ArrayList初始化contentList
class B extends A
{
public B(ArrayList< BContent> content)
{
contentList = content ;
}
...
}
class C扩展了A
{
public C(ArrayList< CContent> content )
{
contentList = content;
}
...
}
我来自Objective-C背景,这可能是由于动态类型解析。如何在Java中实现此功能? 欢呼 您可以使用泛型。 这意味着 I have a superclass A that has a protected Each of B and C initialise contentList in their constructor with ArrayList of different types Both The compiler is complaining that this is not accepted and that I have to change the declaration type of I come from Objective-C background and this is possible due to dynamic type resolution. How can I achieve this in Java? Cheers
AF You could use generics. This means that 这篇关于继承超类的ArrayList属性,但在子类中为其分配不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! BCOntent
和 CContent
和来自Object的数据结构子类。
$ b 编译器抱怨这是不被接受的,我必须将 contentList
的声明类型从 ArrayList< Object>
更改为 ArrayList< BCOntent>
或 ArrayList< CCOntent> $ b
AF
class A< T> {
受保护的列表< T>内容;
}
class B extends A< BContent> {
...
}
A
可以用于不同的可能类型( T
)作为其内容。 A< BContent>
持有 BContent
,并且 A< CContent>
持有 CContent
。ArrayList<Object> contentList
. And I have classes B and C that inherit from A.class B extends A
{
public B (ArrayList<BContent> content)
{
contentList = content;
}
...
}
class C extends A
{
public C (ArrayList<CContent> content)
{
contentList = content;
}
...
}
BCOntent
and CContent
and data structure subclasses from Object.contentList
from ArrayList<Object>
to ArrayList<BCOntent>
or ArrayList<CCOntent>
class A<T> {
protected List<T> content;
}
class B extends A<BContent> {
...
}
A
can be used with different possible types (T
) as its content. A<BContent>
holds BContent
, and A<CContent>
holds CContent
.