Java instanceof演算子で変数が子クラスのインスタンスかどうかを判定するサンプル

環境
JavaSE 1.8
Eclipse 4.14.0

構文
変数名 instanceof クラス名
「instanceof」演算子を使って変数の型を確認します。
instanceofの戻り値はbooleanなので、trueなら指定したクラスやインターフェイスである、falseならそうではない

書式
スーパークラス 変数名 = new 子クラス名()
if(変数名 instanceof 子クラス){処理コード}
instanceof演算子を使って、変数が子クラスのインスタンスかどうかを判定します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
//親クラス
class Person {
}
//子クラス
class Student extends Person {
}
public class TestDemo {
public static void main(String[] args) {
// クラスStudentのインスタンスを作成
Person ps = new Student();
funA(ps);
}
static void funA(Person person) {
// サブクラスStudentのインスタンスかどうか判定
if (person instanceof Student) {
System.out.println("サブクラスPersonのインスタンスです AA");
} else {
System.out.println("サブクラスPersonのインスタンスではない BB");
}
}
}
package com.arkgame.study; //親クラス class Person { } //子クラス class Student extends Person { } public class TestDemo { public static void main(String[] args) { // クラスStudentのインスタンスを作成 Person ps = new Student(); funA(ps); } static void funA(Person person) { // サブクラスStudentのインスタンスかどうか判定 if (person instanceof Student) { System.out.println("サブクラスPersonのインスタンスです AA"); } else { System.out.println("サブクラスPersonのインスタンスではない BB"); } } }
package com.arkgame.study;

//親クラス
class Person {
}
//子クラス
class Student extends Person {
}

public class TestDemo {

      public static void main(String[] args) {
            // クラスStudentのインスタンスを作成
            Person ps = new Student();
            funA(ps);
      }

      static void funA(Person person) {
            // サブクラスStudentのインスタンスかどうか判定
            if (person instanceof Student) {
                  System.out.println("サブクラスPersonのインスタンスです AA");
            } else {
                  System.out.println("サブクラスPersonのインスタンスではない BB");
            }
      }

}

実行結果
サブクラスPersonのインスタンスです AA

Java

Posted by arkgame