Populate arraylist with different objects inherited from multiple classses

22 Views Asked by At

I have class parent A with children B,C,D. Now I have another class E which should have an arraylist containing objects from classes B, C, D.

I thought of class E should extend class A, but I do not know how to add different objects in that arraylist.

1

There are 1 best solutions below

0
Sathyendran a On

Lets have the code like below

class A {
}

class B extends A {}

class C extends A {}

class D extends A {}

Your E class can have instance of list as below

class E {
      List<A> list;
   }

class B,C and E are sub class of A. So this list can hold all the subclass of A

You can assign

 List<A> allSubClass = Arrays.asList(new A(),new B(),new C());