Java instanceof specific usage

Java instanceof specific usage

Keyword

First of all: instanceof is a reserved keyword of Java
keyword!
Keywords!
Keywords!

effect

Its specific function is to test whether the object on the left is an instance object created by the right class or a subclass of this class (or the relationship between the interface and the implementation) .

usage

note! ! !
Any one of the declaration type on the right and the class on the left must be the same branch of the inheritance tree or have an inheritance (implementation) relationship with the test class

Assuming a class relationship:
Insert picture description here

    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); // 无关系

Guess you like

Origin blog.csdn.net/qq_36976201/article/details/112080888