「Java」instanceof演算子でインターフェースの実装クラスのインスタンスを判定するサンプル
書式
実装クラスのオブジェクト名 instanceof インターフェース名
使用例
package com.arkgame.study;
//インターフェースInterParent
interface InterParent {
public String testfunc();
}
//インターフェースを実装するクラスChildDemo
class ChildDemo implements InterParent {
@Override
public String testfunc() {
return "test020";
}
}
public class InterfaceDemo {
public static void main(String[] args) {
//実装クラスのオブジェクト
ChildDemo chA = new ChildDemo();
ChildDemo chB = new ChildDemo();
Boolean result, result2;
result = (chA instanceof InterParent);
System.out.println("実装クラスのインスタンスの比較結果1:" + result);
//インターフェースのインスタンスの判定
result2 = (chB instanceof InterParent);
System.out.println("実装クラスのインスタンスの比較結果2:" + result2);
}
}
package com.arkgame.study;
//インターフェースInterParent
interface InterParent {
public String testfunc();
}
//インターフェースを実装するクラスChildDemo
class ChildDemo implements InterParent {
@Override
public String testfunc() {
return "test020";
}
}
public class InterfaceDemo {
public static void main(String[] args) {
//実装クラスのオブジェクト
ChildDemo chA = new ChildDemo();
ChildDemo chB = new ChildDemo();
Boolean result, result2;
result = (chA instanceof InterParent);
System.out.println("実装クラスのインスタンスの比較結果1:" + result);
//インターフェースのインスタンスの判定
result2 = (chB instanceof InterParent);
System.out.println("実装クラスのインスタンスの比較結果2:" + result2);
}
}
package com.arkgame.study; //インターフェースInterParent interface InterParent { public String testfunc(); } //インターフェースを実装するクラスChildDemo class ChildDemo implements InterParent { @Override public String testfunc() { return "test020"; } } public class InterfaceDemo { public static void main(String[] args) { //実装クラスのオブジェクト ChildDemo chA = new ChildDemo(); ChildDemo chB = new ChildDemo(); Boolean result, result2; result = (chA instanceof InterParent); System.out.println("実装クラスのインスタンスの比較結果1:" + result); //インターフェースのインスタンスの判定 result2 = (chB instanceof InterParent); System.out.println("実装クラスのインスタンスの比較結果2:" + result2); } }
実行結果
実装クラスのインスタンスの比較結果1:true
実装クラスのインスタンスの比較結果2:true