Search code examples
javalistobjectextend

Can I place extended objects in a list in java along with the object it extended from?


So I have two objects A & B, and B extends A.

Is it possible to have both objects in the same ArrayList? Or what will I have to do to be able to do this?


Solution

  • Yes, just use a ArrayList<A> and you can insert objects of B also. Here is an example:

    List<A> list = new ArrayList<A>();
    list.add(new B());