假设我有一个名为 animal
的父类(super class),三个子类分别称为 Dog
, Cat
,和Lion
扩展 animal
类(class)。
然后,我为子类分别创建一个对象,并将它们添加到 ArrayList<animal>
中。 .
当我浏览该列表时,如何区分Dog
或Cat
对象作为 ArrayList
中的每个对象类型为animal
?
最佳答案
您应该使用instanceof
运算符:
if (animal instanceof Dog) {
//something
} else if (animal instanceof Cat) {
//something
} else if (animal instanceof Lion) {
//something
}
但是,如果您确实需要使用它,您应该三思而后行。在大多数情况下,instanceof
是一种糟糕的 OOP 实践。
关于java - 如何判断派生类的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29053298/