Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting ArrayList property from superclass but assigning different types to it in child classes

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

like image 641
Abolfoooud Avatar asked Feb 09 '23 01:02

Abolfoooud


1 Answers

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.

like image 199
khelwood Avatar answered Feb 11 '23 16:02

khelwood