Let's say I have a class A which have some methodes. I then have a class B that extends A, but have a extra variable. Now I want to have an ArrayList of both A and B in another class, so that when I iterate over the list, with i.e. a .getName()
methode, I get the name of both classes? Do I create an ArrayList<A>
and add instances of A and B to it, or do I create an ArrayList<Object>
? In the case of ArrayList<Objects>
, how do I call the .getName()
on the different objects ?
You would create the ArrayList with the type parameter set to A. B inherits all of A's properties and methods, which means that you can access them in B in exactly the same way as you access them in A. If however you want to access a property in B that is not present in A you would have to cast it. For example,
for (A p: aList) {
p.methodFromA();
if (p instanceof B) {
B q = (B) p;
q.methodOnlyBHas();
// or
((B)p).methodOnlyBHas();
}
}
If you created an ArrayList of Objects you would have to cast every element to the class you want. This pretty much negates the idea behind generics and would be no different from creating an ArrayList with no type parameter. You should avoid doing this so that you can get the benefits that generics give you, eg type errors at compile time rather than casting exceptions at runtime.