深入解析Java中的instanceof关键字

1. 引言

在Java编程中,我们经常需要确定一个对象的确切类型。这是instanceof关键字发挥作用的地方。本文将深入探讨它的用途、语法和实际应用,同时揭示一些常见的误区和陷阱。

2. 基本概念

  • 什么是instanceof instanceof关键字用于检查一个对象是否属于特定类或其子类的实例。它的作用是判断一个对象是否是某个类的实例,或者是否实现了某个接口。它可以用于条件判断、类型转换和强制类型检查等场景。

  • instanceof的基本语法:

  • 首先定义三个类GrandFather,Father,Son:

    然后让Father继承GrandFather,Son继承Father,GrandFather默认继承Object

    /*
    * instanceof 关键字
    * 2023/8/21
    * YangJie
     */
    public class test {
        public static void main(String[] args) {
            GrandFather grandFather = new GrandFather();
            Father father = new Father();
            Son son = new Son();
            System.out.println("------------------Object----------------------");
            System.out.println(grandFather instanceof Object);
            System.out.println(father instanceof Object);
            System.out.println(son instanceof Object);
            System.out.println("------------------GrandFather------------------------");
            System.out.println(grandFather instanceof GrandFather);
            System.out.println(father instanceof GrandFather);
            System.out.println(son instanceof GrandFather);
            System.out.println("--------------------Father---------------------");
            System.out.println(grandFather instanceof Father);
            System.out.println(father instanceof Father);
            System.out.println(son instanceof Father);
    
            System.out.println("--------------------Son---------------------");
            System.out.println(grandFather instanceof Son);
            System.out.println(father instanceof Son);
            System.out.println(son instanceof Son);
        }
    }
    

    输出内容:

    ------------------Object----------------------
    true
    true
    true
    ------------------GrandFather-----------------
    true
    true
    true
    --------------------Father--------------------
    false
    true
    true
    --------------------Son-----------------------
    false
    false
    true

    instanceof关键字判断后是有返回值的且返回值为boolean类型

  • 因为所有的类都直接或者间接的继承了Object,都算是Object类的子类,所以控制台输出结果都为true

  • 把instanceof后面的类型换成GrandFather类型时会发现 控制台输出结果仍然全是true

  • 把instanceof后面的类型换成Father类型时会发现 控制台输出结果第一个为false后两个是true

  • 把instanceof后面的类型换成Father类型时会发现 控制台输出结果前两个为false最后一个是true

  • 结语:由此我们可以确定instanceof前面的对象所属的类是后面类型的类或者是其子类的话,判断结果为true,否则为false

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dr_eamboat

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值