「Java」instanceof演算子の右辺がインタフェースのインスタンス型を判定

2022年1月17日

書式
変数 instanceof インターフェース名
変数が参照しているインスタンスは、インターフェース名の実装クラスのインスタンスです
変数が参照しているインスタンスは、インターフェース名の実装クラスのサブクラスのインスタンスです
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package info;
//インタフェースInterTestAの定義
interface InterTestA {
int age = 11;
}
//インターフェースを実装する
class TestA implements InterTestA {
String username = "tokyo";
}
public class InstanceofDemo {
public static void main(String[] args) {
//インスタンスの生成
TestA cft = new TestA();
Boolean result;
//インスタンスの判定
result = cft instanceof InterTestA;
System.out.println(result);
}
}
package info; //インタフェースInterTestAの定義 interface InterTestA { int age = 11; } //インターフェースを実装する class TestA implements InterTestA { String username = "tokyo"; } public class InstanceofDemo { public static void main(String[] args) { //インスタンスの生成 TestA cft = new TestA(); Boolean result; //インスタンスの判定 result = cft instanceof InterTestA; System.out.println(result); } }
package info;

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

//インターフェースを実装する
class TestA implements InterTestA {
      String username = "tokyo";
}

public class InstanceofDemo {

      public static void main(String[] args) {
            //インスタンスの生成
            TestA cft = new TestA();
            Boolean result;
            //インスタンスの判定
            result = cft instanceof InterTestA;

            System.out.println(result);

      }

}

実行結果
true

Java

Posted by arkgame