Not sure if the title makes sense, I will try to explain. I have a CustomList extending ArrayList, T being let's say Class A1 and Class A2, both extending Class A which is a custom Class.
I need to do this :
public class CustomList<T> extends ArrayList<T>
{
public CustomList()
{
super();
}
public boolean add(T obj)
{
/*The method getCustomBoolean() is not defined for the type T*/
if(obj.getCustomBoolean())
{
super.add(obj);
}
return true;
}
}
The method getCustomBoolean()
is a Class A
method, and using this CustomList only for A1
and A2
, I'm sure obj.getCustomBoolean()
won't cause an exception.
I need a way to specify that T is a child class of A.
If you will be only using this CustomList with subclasses of A, than you can declare the CustomList class as:
But if not, than you have to rethink your design.
Change the very first line of your class to this.
That specifies that
T
can be any type which is a subtype ofA
. It will allow you to use methods of typeA
on yourT
object, within your class's code.Do it this way:
Use:
This works fine:
Note that if you extend
ArrayList<A>
you can add items of typeA1
orA2
but if you extendArrayList<T>
you will be restricted to the type in the declaration.