[Java]instanceofでインタフェースのインスタンスを判定するサンプル

2021年4月14日

書式
オブジェクト名 instanceof インタフェース名
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
//インターフェースParentの定義
interface Parent {
int age = 12;
}
// インターフェースの実装
class Cft implements Parent {
String Parentname = "yamada";
}
//Cftクラスの継承
class Child extends Cft {
double sa = 21.34;
}
//動作確認mainクラス
public class InstanceChild {
public static void main(String[] args) {
// オブジェクトの作成
Child cd = new Child();
boolean flg;
// インタフェースの判定
flg = cd instanceof Parent;
System.out.println("インターフェースParentのインスタンスの判定結果: " + flg);
}
}
package com.arkgame.study; //インターフェースParentの定義 interface Parent { int age = 12; } // インターフェースの実装 class Cft implements Parent { String Parentname = "yamada"; } //Cftクラスの継承 class Child extends Cft { double sa = 21.34; } //動作確認mainクラス public class InstanceChild { public static void main(String[] args) { // オブジェクトの作成 Child cd = new Child(); boolean flg; // インタフェースの判定 flg = cd instanceof Parent; System.out.println("インターフェースParentのインスタンスの判定結果: " + flg); } }
package com.arkgame.study;

//インターフェースParentの定義
interface Parent {
      int age = 12;
}

// インターフェースの実装
class Cft implements Parent {
      String Parentname = "yamada";
}

//Cftクラスの継承
class Child extends Cft {
      double sa = 21.34;
}

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

      public static void main(String[] args) {
            // オブジェクトの作成
            Child cd = new Child();
            boolean flg;
            // インタフェースの判定
            flg = cd instanceof Parent;
            System.out.println("インターフェースParentのインスタンスの判定結果: " + flg);

      }
}

実行結果
インターフェースParentのインスタンスの判定結果: true

Java

Posted by arkgame