instanceof
オブジェクトが特定のクラスの直接インスタンスであるか子孫インスタンスであるかをテストするために使用できます。instanceof
インターフェイスをクラスのようにインスタンス化できない場合でも、インターフェイスで使用することもできます。誰かがどのように機能するか説明できますinstanceof
か?
8 に答える
まず、特定のものをこのようにinstances
実装するクラスを格納できます。interface
interface reference variable
package com.test;
public class Test implements Testable {
public static void main(String[] args) {
Testable testable = new Test();
// OR
Test test = new Test();
if (testeable instanceof Testable)
System.out.println("instanceof succeeded");
if (test instanceof Testable)
System.out.println("instanceof succeeded");
}
}
interface Testable {
}
つまり、特定のインターフェイスを実装するランタイム インスタンスはすべてinstanceof
テストに合格します。
編集
そして出力
instanceof succeeded
instanceof succeeded
@RohitJain
このような匿名の内部クラスを使用して、インターフェイスのインスタンスを作成できます
Runnable runnable = new Runnable() {
public void run() {
System.out.println("inside run");
}
};
instanceof
そして、このような演算子を使用して、インスタンスがインターフェイス型であることをテストします
System.out.println(runnable instanceof Runnable);
結果は「true」です
object instanceof object_interface
お譲り致しtrue
ます。
に対してinstanceof
a のチェックを行うと、その特定の型が指していることがチェックされます。reference
instance
instance
reference
interface
これで、実装のインスタンスを指すの参照を作成できるようになりました( を指すのclass
と同じ概念)。それで、あなたはそれをチェックすることができます。Super class reference
subclass instance
instanceof
例:-
public interface MyInterface {
}
class ImplClass implements MyInterface {
public static void main(String[] args) {
MyInterface obj = new ImplClass();
System.out.println(obj instanceof ImplClass); // Will print true.
}
}
instanceof 演算子は、最初の引数が 2 番目の引数を実装するオブジェクトであるかどうかを示します。インターフェイスを直接インスタンス化できないことがなぜ重要なのか理解できません。
Integer num = 1;
if (num instanceof Number) {
System.out.println("An integer is a number!");
}
それだけです。