I have class Parent and a subclass Child. I want to make an ArrayList where I can store objects of both these classes. Is something like that possible?
I tried following:
ArrayList<Parent> list= new ArrayList<Parent>();
Parent a;
Parent b;
Child c;
list.add(a);
list.add(b);
list.add(c);
To this point the compiler didn't get me any errors, so I suppose it is ok. But when i try to use a method from Child on an object that i got from the ArrayList I am not able to use it! While
list.get(2).countNumbers();
This gets me an error, the method countNumbers is in Child.I am very confused, thank you in advance!
The ArrayList<Parent>
is a container of Parent
, so you can put any object that is a Parent
in it. A Child
is of cource a Parent
, so the ArrayList<Parent>
can receive it.
However, since your ArrayList<Parent>
only knows that it contains Parent
, it has no idea whether an object in it is a Child
or not. So the compiler won't allow you to treat the elements in it as Child
ren, though it may be a Child
at runtime. So if you are sure that the Parent
object is also a Child
, you can downcast it by Child child = (Child) object;
. Then you can treat it as a Child
at compile time. But note that downcast is not type safe, and it may throw runtime exceptions.
You want to declare your List:
List<Parent> list = new ArrayList<>();
This will tell Java that you accept any Class extending or being Parent.
Since the List
will contain Parent
types, to use a Child
object, you have to cast it:
Parent o = list.get(x);
if (o instanceof Child) {
Child child = (Child) o;
// Do something with child
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.