Java-[instanceof]

FangShiRui 2020-07-28 PM 2017℃ 0条

用途

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

代码

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
        
    }
}
标签: none

非特殊说明,本博所有文章均为博主原创。

上一篇 Java-注解
下一篇 基本UML入门

评论已关闭