instanceof 如何在接口上工作 [英] How instanceof will work on an interface
问题描述
instanceof
可用于测试对象是给定类的直接实例还是后代实例.instanceof
也可以与接口一起使用,即使接口不能像类一样被实例化.谁能解释一下 instanceof
是如何工作的?
instanceof
can be used to test if an object is a direct or descended instance of a given class. instanceof
can also be used with interfaces even though interfaces can't be instantiated like classes. Can anyone explain how instanceof
works?
推荐答案
首先,我们可以在中存储实现特定
像这样.interface
的类的instances
>接口引用变量
First of all, we can store instances
of classes that implements a particular interface
in an interface reference variable
like this.
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
测试
ie, any runtime instance that implements a particular interface will pass the instanceof
test
编辑
和输出
instanceof succeeded
instanceof succeeded
@RohitJain
你可以像这样使用匿名内部类来创建接口的实例
You can create instances of interfaces by using anonymous inner classes like this
Runnable runnable = new Runnable() {
public void run() {
System.out.println("inside run");
}
};
并且您测试实例是接口类型,使用像这样的 instanceof
运算符
and you test the instance is of type interface, using instanceof
operator like this
System.out.println(runnable instanceof Runnable);
结果为真"
这篇关于instanceof 如何在接口上工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!