Skip to content
Advertisement

Java: how to have an array of subclass types?

Say I have a super class “Animal” and subclasses “Cat”, Dog, Bird”. Is there a way to have an array of subclass type rather than class instances with which I’ll be able to instantiate instances of each possible subclass?

To simplify, I want this:

Pseudo code: For each possible subclass of "Animal": create an instance of that class.

How can I do that?

Edit: I don’t want an array of instances of these subclasses, I want an array of object type.

Advertisement

Answer

After OP’s comment
THERE IS NO WAY TO GET ALL SUBTYPES OF A CLASS even using reflection.
But you can do it by another way , you can say which is the only but longest way.

  • Get a list of names of all classes that exist on the class path
  • Load each class and test to see if it is a subclass or implementor of the desired class or interface



Answer before OP’s comment

As your question is not clear yet but I guess you want to use array or Collection which will store all of the instances even it is the instance of superclass or subclass.
Then I guess you need to do like this.

List<Object> list = new ArrayList<Object>();
         list.add(new Cat());
         list.add(new Dog());
         list.add(new Animal());
         list.add(new Cat());

         for (int i = 0; i < list.size(); i++) {

             if(list.get(i) instanceof Cat){
                 System.out.println("Cat at "+i);
             }else if(list.get(i) instanceof Dog){
                 System.out.println("Dog at "+i);
             }else if(list.get(i) instanceof Animal){
                 System.out.println("Animal at "+i);
             }
        }

This code is tested
Note: Keep in mind that Don’t place parent class check like in case of example code (list.get(i) instanceof Animal) at top, otherwise it will pass both cases (if checks are only if-if-if) or skip one case(and always return the object as a Animal if checks are if-else if-else if) (list.get(i) instanceof Animal) and (list.get(i) instanceof Cat) If the returning object is a Cat object.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement