加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

检查数组中的元素是否是Java中的SubClass

发布时间:2020-12-14 06:01:50 所属栏目:Java 来源:网络整理
导读:让我们假设我想检查Object数组中的值是否属于超类或子类,例如我的超类叫Called Animal,我声明了一个类型为Animal的数组 Animal myAnimals[] = new Animal[]; 现在假设有像Lion,Tiger,Elephant等动物的子类.如果我要遍历数组,我如何区分子类(Lion,Tiger等)和
让我们假设我想检查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.
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读