Java:如何判断对象是否属于特定子类。
我想检查一个对象是否属于特定的子类,并且对于从同一父类(super class)继承的其他类,检查不会返回 true。
所以,例如:
父类(super class):水果
子类:苹果和香蕉延长果实
然后我检查一下(if appleObject.isThisClass(apple)){do stuff}
到目前为止,我所能找到的所有方法都是检查是否仍会返回 true 的方法,因为它们共享相同的父类(super class)。
希望这是有道理的。
感谢您的帮助。
最佳答案
假设您有一个 Banana 或 Apple 类型的对象引用 apple
;然后是这样的,
if (apple instanceof Apple) // true
告诉您 apple
是否属于 Apple
类型。在哪里
if (apple instanceof Banana) // false
会排除Banana
,最后
if (apple instanceof Fruit) // true
将包括Banana
或Apple
;但您可能不应该在调用方 ( tight coupling ) 中对此进行测试 - 相反,您应该尝试将行为封装在 Fruit
“接口(interface)”中。
编辑
鉴于您在评论中提出的其他问题,
Fruit aFruit = aMethod(); // get a fruit.
if (aFruit instanceof Apple) {
Apple apple = (Apple) aFruit;
// do apple things with the apple.
apple.somethingOnlyApplesDo();
} // else if (aFruit instanceof Banana) {
// Do Nothing With Bananas.
// Banana banana = (Banana) aFruit;
// }
关于Java:如何判断一个对象是否属于特定的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23025248/