「Java」instanceofでクラスのインスタンスを判定するサンプル

2021年4月14日

書式
オブジェクト instanceof クラス
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
//親クラスUser
class User {
int age = 12;
// コンストラクタ
public User(int age) {
this.age = age;
}
}
//子クラスの定義
class Student extends User {
String username = "yamada";
// コンストラクタ
public Student(int age) {
super(age);
}
}
//動作確認mainクラス
public class InstanceOfDemo {
public static void main(String[] args) {
User usr = new User(35);
Student stu = new Student(25);
boolean flg;
flg = usr instanceof User;
System.out.println("クラスUserのインスタンス: " + flg);
flg = usr instanceof Student;
System.out.println("クラスUserのインスタンス: " + flg);
System.out.println("***********************");
flg = stu instanceof Student;
System.out.println("クラスStudentのインスタンス: " + flg);
flg = stu instanceof User;
System.out.println("クラスStudentのインスタンス: " + flg);
}
}
package com.arkgame.study; //親クラスUser class User { int age = 12; // コンストラクタ public User(int age) { this.age = age; } } //子クラスの定義 class Student extends User { String username = "yamada"; // コンストラクタ public Student(int age) { super(age); } } //動作確認mainクラス public class InstanceOfDemo { public static void main(String[] args) { User usr = new User(35); Student stu = new Student(25); boolean flg; flg = usr instanceof User; System.out.println("クラスUserのインスタンス: " + flg); flg = usr instanceof Student; System.out.println("クラスUserのインスタンス: " + flg); System.out.println("***********************"); flg = stu instanceof Student; System.out.println("クラスStudentのインスタンス: " + flg); flg = stu instanceof User; System.out.println("クラスStudentのインスタンス: " + flg); } }
package com.arkgame.study;

//親クラスUser
class User {
      int age = 12;

      // コンストラクタ
      public User(int age) {
            this.age = age;
      }
}

//子クラスの定義
class Student extends User {
      String username = "yamada";

      // コンストラクタ
      public Student(int age) {
            super(age);
      }

}

//動作確認mainクラス
public class InstanceOfDemo {

      public static void main(String[] args) {
            User usr = new User(35);
            Student stu = new Student(25);
            boolean flg;
            flg = usr instanceof User;
            System.out.println("クラスUserのインスタンス: " + flg);

            flg = usr instanceof Student;
            System.out.println("クラスUserのインスタンス: " + flg);

            System.out.println("***********************");

            flg = stu instanceof Student;
            System.out.println("クラスStudentのインスタンス: " + flg);
            flg = stu instanceof User;
            System.out.println("クラスStudentのインスタンス: " + flg);

      }

}

実行結果
クラスUserのインスタンス: true
クラスUserのインスタンス: false
***********************
クラスStudentのインスタンス: true
クラスStudentのインスタンス: true

Java

Posted by arkgame