用途

判断对象是否是目标类或者目标类的子类。
如果对象与目标类属于同级的类,则无法比较。编译报错。

代码

public  class Person {
    private String name ;

    public void say(){
        System.out.println("this is a person");
    }
    
}

class Student extends Person{
    @Override
    public void say() {
        System.out.println("this is a student");
    }
    public void study(){
        System.out.println("学习");
    }
}

class Test{
    public static void main(String[] args) {
        Person a = new Student();  // a丢失study方法
        System.out.println(a.getClass());  // Student

        System.out.println(a instanceof Person);  // true
        System.out.println(a instanceof Object); // true
        
        a = new Person();
        System.out.println(a instanceof Student); // false
        
    }
}
最后修改:2020 年 07 月 28 日
如果觉得我的文章对你有用,请随意赞赏