So basically I've created two classes "public class A" and "public class B extends A". I want to create an ArrayList that contains both objects and be able to access both of their methods. Is this possible and how could I do it?
-
1You have an `Animal` and a `Dog` (which is an animal) class and you want an `arraylist` to hold both of them. What should be type of arraylist ? `Animal` or `Dog` ? This is best I can do without giving you an actual answer. – Prateek Nov 20 '13 at 00:20
-
[This](http://stackoverflow.com/questions/3009745/what-does-the-question-mark-in-java-generics-type-parameter-mean) might answers your question. – MZ4Code Nov 20 '13 at 00:22
2 Answers
An ArrayList<B> won't hold objects of type A, so that can't work.
An ArrayList<? extends A> won't work either. The compiler won't know which subtype of A (or A itself) it really is, so it won't allow adding anything but null with the add method.
Generally the best you can do is to use an ArrayList<A>.
There could be methods that are defined in A but not B. Here B simply inherits the A method and can be called using an A reference.
There could be methods that are defined in both A and B. Here B overrides A's method. Polymorphism indicates that B's method will be called on objects whose runtime type is B.
There could be methods that are defined only in B. With an A reference they are inaccessible. But at runtime you can check the type with instanceof:
for (A a : arrayList)
{
if (a instanceof B)
{
B b = (B) a;
b.methodSpecificToB();
}
}
- 176,041
- 30
- 275
- 357
ArrayList<A> myArray;
This array list will hold objects of type A and type B.
- 5,588
- 4
- 33
- 56