class Animal {}
class Dog extends Animal {}
public class Main {
public static void main(String[] args) {
Object obj = new Dog();
System.out.println(obj instanceof Animal);
System.out.println(obj instanceof Dog);
}
}
選択肢
- あなたの回答
- 正解
正解
A. true / true
詳細解説
instanceof は実体のクラスとその全スーパータイプを true と判定します。Dog は Animal を継承しているため obj instanceof Animal も obj instanceof Dog もどちらも true です。
なぜ他の選択肢が違うのか
- Dog は Animal を継承しているため instanceof Animal も true になります。
- 実体が Dog なので instanceof Dog は true です。
- どちらも実体 Dog の継承階層に含まれるため true になります。
罠ポイント
instanceof は変数の宣言型ではなく実行時の実体に基づいて判定されます。