「Java」インターフェースの実装クラスの子クラスのインスタンスを判定するサンプル

2021年1月18日

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study;
//インターフェースInterParent
interface InterParentDemo {
public static final int age = 0;
public String testfunc();
}
//インターフェースを実装するクラスChildDemoA
class ChildDemoA implements InterParentDemo {
String msg;
@Override
public String testfunc() {
return "test020";
}
}
//クラスChildDemoAの継承
class ChildDemoB extends ChildDemoA {
String username;
}
public class InterfaceImpleDemo {
public static void main(String[] args) {
// 実装クラスのオブジェクトA
ChildDemoA chA = new ChildDemoA();
Boolean result;
result = (chA instanceof InterParentDemo);
System.out.println("結果1:" + result);
// 実装クラスのオブジェクトB
ChildDemoB chB = new ChildDemoB();
Boolean result2;
// インターフェースのインスタンスの判定
result2 = (chB instanceof InterParentDemo);
System.out.println("結果2:" + result2);
}
}
package com.arkgame.study; //インターフェースInterParent interface InterParentDemo { public static final int age = 0; public String testfunc(); } //インターフェースを実装するクラスChildDemoA class ChildDemoA implements InterParentDemo { String msg; @Override public String testfunc() { return "test020"; } } //クラスChildDemoAの継承 class ChildDemoB extends ChildDemoA { String username; } public class InterfaceImpleDemo { public static void main(String[] args) { // 実装クラスのオブジェクトA ChildDemoA chA = new ChildDemoA(); Boolean result; result = (chA instanceof InterParentDemo); System.out.println("結果1:" + result); // 実装クラスのオブジェクトB ChildDemoB chB = new ChildDemoB(); Boolean result2; // インターフェースのインスタンスの判定 result2 = (chB instanceof InterParentDemo); System.out.println("結果2:" + result2); } }
package com.arkgame.study;

//インターフェースInterParent
interface InterParentDemo {
      public static final int age = 0;

      public String testfunc();
}

//インターフェースを実装するクラスChildDemoA
class ChildDemoA implements InterParentDemo {
      String msg;

      @Override
      public String testfunc() {
            return "test020";
      }

}

//クラスChildDemoAの継承
class ChildDemoB extends ChildDemoA {
      String username;

}

public class InterfaceImpleDemo {

      public static void main(String[] args) {

            // 実装クラスのオブジェクトA
            ChildDemoA chA = new ChildDemoA();
            Boolean result;
            result = (chA instanceof InterParentDemo);
            System.out.println("結果1:" + result);
            
            // 実装クラスのオブジェクトB
            ChildDemoB chB = new ChildDemoB();
            Boolean result2;
            // インターフェースのインスタンスの判定
            result2 = (chB instanceof InterParentDemo);
            System.out.println("結果2:" + result2);

      }

}

実行結果
結果1:true
結果2:true

Java

Posted by arkgame