让我们假设我想检查Object数组中的值是否属于超类或子类,例如我的超类叫Called Animal,我声明了一个类型为Animal的数组
Animal myAnimals[] = new Animal[];
现在假设有像Lion,Tiger,Elephant等动物的子类.如果我要遍历数组,我如何区分子类(Lion,Tiger等)和超类Animal?谢谢!
解决方法
使用
instanceof
At run time,the result of the instanceof operator is true if […]
the reference could be cast (§15.16) to the ReferenceType without
raising a ClassCastException.
for (Animal a : myAnimals) { if (a instanceof Lion) System.out.println("Lion"); // etc. }