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 ?

- 597
- 2
- 10
- 33
-
1If I'm understanding your intent correctly, you should be able to use `ArrayList` since B is a subclass of A. If both classes have a `getName()` method (B will inherit the method from A, but you may also choose to override it), you would just need a loop to iterate through your `ArrayList` and call the `getName()` method for each object in the `ArrayList`. – Calvin P. Dec 02 '15 at 14:39
2 Answers
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.

- 1,284
- 1
- 12
- 23
-
But what if i want to print out the object, i.e. that A got som variables called `name, size, color` and B got the same, but also have the variable ` weight `, how do I get all of the variables from A and all from B? Like: `For(A p: aList){ print(p) }` but i also want to print the object of type B in the `ArrayList` ? If it makes sense.. – Lasse Dec 02 '15 at 14:52
-
1I have updated the answer so that I could add a code example, hope that helps – ewanc Dec 02 '15 at 15:06
-
1
ArrayList<A>
will work for both A and B, no need to go for more generalization, i.e Object.
How to call getName()
depends on where getName()
is defined.
If it's in A
, you could call it in all the objects in the ArrayList
, but if the method is only in B
, you may have to check the instanceof B
and then call the method.

- 5,021
- 5
- 26
- 37