instanceof如何在接口上工作


问题内容

instanceof可用于测试对象是给定类的直接实例还是后代实例。instanceof即使接口不能像类一样实例化,也可以与接口一起使用。谁能解释instanceof工作原理?


问题答案:

首先,我们可以存储instances这样实现特定功能interfaceinterface reference variable类。

package com.test;

public class Test implements Testeable {

    public static void main(String[] args) {

        Testeable testeable = new Test();

        // OR

        Test test = new Test();

        if (testeable instanceof Testeable)
            System.out.println("instanceof succeeded");
        if (test instanceof Testeable)
            System.out.println("instanceof succeeded");
    }
}

interface Testeable {

}

即,任何实现特定接口的运行时实例都将通过instanceof测试

编辑

和输出

instanceof succeeded
instanceof succeeded

@RohitJain

您可以通过使用这样的匿名内部类来创建接口的实例

Runnable runnable = new Runnable() {

    public void run() {
        System.out.println("inside run");
    }
};

然后使用instanceof类似的运算符测试实例的类型为interface

System.out.println(runnable instanceof Runnable);

结果为“ true”