继承超类的ArrayList属性,但在子类中为其分配不同的类型 [英] Inheriting ArrayList property from superclass but assigning different types to it in child classes

查看:78
本文介绍了继承超类的ArrayList属性,但在子类中为其分配不同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超类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;
}
...
}

BCOntent CContent 和来自Object的数据结构子类。
$ b 编译器抱怨这是不被接受的,我必须将 contentList 的声明类型从 ArrayList< Object> 更改为 ArrayList< BCOntent> ArrayList< CCOntent> $ b

我来自Objective-C背景,这可能是由于动态类型解析。如何在Java中实现此功能?



欢呼
AF

解决方案

您可以使用泛型。

  class A< T> {
受保护的列表< T>内容;
}

class B extends A< BContent> {
...
}

这意味着 A 可以用于不同的可能类型( T )作为其内容。 A< BContent> 持有 BContent ,并且 A< CContent> 持有 CContent


I have a superclass A that has a protected ArrayList<Object> contentList. And I have classes B and C that inherit from A.

Each of B and C initialise contentList in their constructor with ArrayList of different types

class B extends A
{
    public B (ArrayList<BContent> content)
    {
        contentList = content;
    }
...
}


class C extends A
{
    public C (ArrayList<CContent> content)
    {
        contentList = content;
    }
...
}

Both BCOntent and CContent and data structure subclasses from Object.

The compiler is complaining that this is not accepted and that I have to change the declaration type of contentListfrom ArrayList<Object> to ArrayList<BCOntent> or ArrayList<CCOntent>

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.

class A<T> {
    protected List<T> content;
}

class B extends A<BContent> {
    ...
}

This means that A can be used with different possible types (T) as its content. A<BContent> holds BContent, and A<CContent> holds CContent.

这篇关于继承超类的ArrayList属性,但在子类中为其分配不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆