Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 930
Mickael Bergeron Néron Avatar asked Jan 13 '23 21:01

Mickael Bergeron Néron


2 Answers

You can use Ploymorphism to achieve that.

Animal[] animalArray = new Animal[10];
animalArray[0] = new Dog();
animalArray[1] = new Cat();

Basically all subclasses of animal Class. When you want to retrieve the objects you can simply typecaset it

Dog dog = (Dog)animalArray[0];

To know the class you can simple use getClass() method. For example

    Animal[] animalArray = new Animal[10];
    animalArray[0] = new Dog();
    System.out.println(animalArray[0].getClass());

will print class Dog.

like image 149
Aniket Thakur Avatar answered Jan 19 '23 02:01

Aniket Thakur


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.

like image 26
Freak Avatar answered Jan 19 '23 02:01

Freak