![](/img/trans.png)
[英]In Java, how do I make instance variables of a subclass have the type of the subclass, rather than of the superclass?
[英]Java, instanceof a subclass rather than a superclass
我知道如果不得不問這個問題,我的程序可能設計不佳。 如何確定對象是子類類型而不是子類的父類?
例如:
if (r instanceof subclassRobot) {
//method
}
如果r
是父級,我不希望執行此操作。 我只希望如果r
是子類類型,則執行此方法。
您可以像這樣檢查類本身:
if(thing instanceof SomeClass.class && !thing.getClass().equals(SomeClass.class))
{
// Thing can be any class that extends SomeClass,
// but will not belong to SomeClass itself.
}
r.getClass().equals(subClass.class)
絕對好的代碼。
您的p是對屬於基類族的類族的引用。 O操作。
if (r instanceof subclassRobot) {
//...
}
可以很好地檢查您是否實際上指向subclassRobot
的實例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.