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?
推荐答案首先,我们可以在接口引用变量$中存储实现特定接口的类的实例 c $ c>喜欢这个。
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 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 test
ie, any runtime instance that implements a particular interface will pass the instanceof test
编辑
和输出
instanceof succeeded instanceof succeeded@RohitJain
@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 这样的运算符
System.out.println(runnable instanceof Runnable);,结果为'true'
更多推荐
instanceof如何在接口上工作
发布评论