instanceof 的使用

//父类
package oop.demo08;

public class Person {
    public void run(){
        System.out.println("run");
    }
}

//子类
package oop.demo08;

public class Student extends Person{
    public void go(){
        System.out.println("go");
    }

}

//子类
package oop.demo08;

public class Teacher extends Person{
}

//测试
//instanceof的使用
    //x instanceof y 能否编译通过,取决于x和y是否存在父子关系
    public static void main(String[] args) {
        //Object > String
        //Object>Person>Student
        //Object>Person>Teacher
        Object object= new Student();

        System.out.println(object instanceof Student);//true
        System.out.println(object instanceof Person);//true
        System.out.println(object instanceof Object);//true
        System.out.println(object instanceof Teacher);//false
        System.out.println(object instanceof String);//false
        System.out.println("==================");

        Person person=new Student();
        System.out.println(person instanceof Student);//true
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Object);//true
        System.out.println(person instanceof Teacher);//false
//        System.out.println(person instanceof String);//编译报错

        System.out.println("===================");


    }

 

posted @ 2022-02-04 17:47  狂神大鑫  阅读(52)  评论(0)    收藏  举报