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 contentList
from 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With