「Java」instanceof演算子で指定クラス(子クラス、親クラス)のインスタンスを判定するサンプル
構文
オブジェクトの変数 instanceof サブクラス
オブジェクトの変数  instanceof 親クラス
1.親クラスの定義
package com.arkgame.study.java;
// class definition
public class EmpParentDemo {
      String empId;
      Integer age;
      // parent constructor
      public EmpParentDemo(String empId, Integer age) {
            this.empId = empId;
            this.age = age;
      }
}
2.子クラスの定義
package com.arkgame.study.java;
// child class extends
public class EmpChildDemo extends EmpParentDemo {
      String depId;
      // child class constructor
      public EmpChildDemo(String empId, Integer age, String depId) {
            super(empId, age);
            this.depId = depId;
      }
}
3.実行確認(main)
package com.arkgame.study.java;
public class EmpSuperMethod {
      public static void main(String[] args) {
            // child object statement
            EmpChildDemo eCh = new EmpChildDemo("A001", 32, "AB");
            // instanceof 子クラス
            boolean resA = eCh instanceof EmpChildDemo;
            // instanceof 親クラス
            boolean resB = eCh instanceof EmpParentDemo;
            System.out.println("オブジェクトeChが子クラスのインスタンス: " + resA);
            System.out.println("オブジェクトeChが親クラスのインスタンス: " + resB);
      }
}
4.実行結果
オブジェクトeChが子クラスのインスタンス: true
オブジェクトeChが親クラスのインスタンス: true