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

2021年4月14日

書式
子クラスのインスタンス名 instanceof 親クラス名
使用例

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

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

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

//子クラスの定義
class Child extends Parent {
      String Parentname = "yamada";

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

}

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

      public static void main(String[] args) {
            Child stu = new Child(25);
            boolean flg;
            flg = stu instanceof Child;
            System.out.println("********子クラスのインスタンスの判定*************");
            System.out.println("クラスChildのインスタンス: " + flg);
            
            flg = stu instanceof Parent;
            System.out.println("クラスParentのインスタンス: " + flg);

      }

}

実行結果
********子クラスのインスタンスの判定*************
クラスChildのインスタンス: true
クラスParentのインスタンス: true

Java

Posted by arkgame