java instanceof具体用法

java instanceof具体用法

关键字

首先:instanceof是Java的一个保留关键字
关键字!
关键字!
关键字!

作用

它的具体作用是测试左边的对象是否是右边类或者该类的子类(或者是接口与实现的关系) 创建的实例对象。

用法

注意!!!
右边的声明类型和左边的类其中的任意一个跟测试类必须得是继承树的同一分支或存在继承(实现)关系

假设有类关系:
在这里插入图片描述

    Object o = new Student(); // 主要看这个对象是什么类型与实例化的类名
    // instanceof关键字可以判断左边对象是否是右边类或者子类的一个实例
    System.out.println(o instanceof Student); // o 是Student类的一个实例对象 所以判断右边类跟student有无关系 以及显示声明有无关系
    System.out.println(o instanceof Person); // true
    System.out.println(o instanceof Object); // true
    System.out.println(o instanceof String); // false
    System.out.println(o instanceof Teacher); // 无关系
    System.out.println("========================");
    
    Person person = new Student();
    System.out.println(person instanceof Person); // true
    System.out.println(person instanceof Object); // true
    // System.out.println(person instanceof String); // 编译错误,Person和String没有继承关系
    System.out.println(person instanceof Teacher); // 无关系

猜你喜欢

转载自blog.csdn.net/qq_36976201/article/details/112080888