instanceof如何在接口上工作

编程入门 行业动态 更新时间:2024-10-24 02:36:00
本文介绍了instanceof如何在接口上工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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?

推荐答案

首先,我们可以在接口引用变量喜欢这个。

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如何在接口上工作

本文发布于:2023-11-04 05:34:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557084.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   如何在   工作   instanceof

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!