【Java】instanceof的使用说明及实例讲解

154 阅读2分钟

本文已参与[新人创作礼]活动,一起开启掘金创作之路。

哈喽,大家好!我是Why,一名在读学生,目前刚刚开始进入自己的编程学习生涯。虽然学习起步较晚,但我坚信做了才有0或1的可能。学了一段时间以后也是选择在掘金上分享自己的日常笔记,也希望能够在众多道友的大家庭中打成一片。 本文主要讲解instanceof的使用说明及实例讲解,如果大家读后觉得有用的话,还请大家多多支持博主:欢迎 ❤️点赞👍、收藏⭐、留言💬 ✨✨✨个人主页:JinHuan

instanceof

instanceof 是java的一个保留关键字

使用方法

object instanceof Class | Interface

返回值类型: boolean

true :代表左边对象是右边的 类\接口 或者其 子类\接口 的 实例化对象\实现类

使用场景

存在继承关系的类或者接口之间

向下进行转型的判断

注意事项(以类为例子,接口和类一样)

在编译阶段的时候:

​ 如果object是Class 的实例、子类或者父类均可以通过编译

运行阶段:

​ object是Class的实例或者子类的时候,返回值为true,为Class的父类时,返回值为false

​ 举个例子:所有的猫咪都是动物,但是不能说所有的动物都是猫咪

栗子

package com.blog.instanceoftest;

import com.sun.org.apache.bcel.internal.generic.FADD;

/**
 * @Author jinhuan
 * @Date 2022/3/23 16:47
 * Description:
 */
public class Test01 {
    public static void main(String[] args) {
        Father father = new Father();
        System.out.println(father instanceof SuperFather);
        System.out.println(father instanceof Father);
        System.out.println(father instanceof Comparable);
        System.out.println(father instanceof Son);
    }
}

/*
	定义一"族" 类 
*/
class SuperFather{}
class Father extends SuperFather implements Comparable{
    @Override
    public int compareTo(Object o) {
        return 0;
    }
}
class Son extends Father{}

image-20220323170333924

package com.blog.instanceoftest;

/**
 * @Author jinhuan
 * @Date 2022/3/23 16:57
 * Description:
 */
public class Test02 {
    public static void main(String[] args) {
        FatherImpl father = new FatherImpl();

        System.out.println(father instanceof SuperFather);
        System.out.println(father instanceof Father);
        System.out.println(father instanceof Son);
    }
}

/*
	定义一"族" 接口 
*/
interface SuperFather{}
interface Father extends SuperFather {}
interface Son extends Father{}

class FatherImpl implements Father{

}

image-20220323170317613

以上均为本人个人观点,借此分享。如有不慎之处,劳请各位批评指正!鄙人将不胜感激并在第一时间进行修改!另外,我自己整理了一些自资源(笔记、书籍、软件等)分享在我的公众号上,非常欢迎大家来访白嫖和博主做朋友,一起学习进步!最后别忘啦支持一下博主哦,求三连!❤️❤️❤️

image-20220428105519763