Check whether the elements in the array are subclasses in Java

Let's assume that I want to check whether the values in the object array belong to a superclass or subclass. For example, my superclass is called animal, and I declare an array of type animal

Animal myAnimals[] = new Animal[];

Now suppose there are subclasses of animals like lion, tiger and elephant If I want to traverse an array, how can I distinguish between the molecular class (lion, tiger, etc.) and the superclass animal? thank you!

Solution

Using instanceof

for (Animal a : myAnimals) {
    if (a instanceof Lion) System.out.println("Lion");
    // etc.
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>