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.
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
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With