instanceof

用于判断一个对象是否属于相应类型

public class Application {
    static void main(String[] args) {
        Student s1 = new Student();
        Person s2 = new Student();
        Object s3 = new Student();

        System.out.println(s3 instanceof Student);
        System.out.println(s3 instanceof Person);
        System.out.println(s3 instanceof Object);
        System.out.println(s3 instanceof Teacher);
        System.out.println(s3 instanceof String);
        //编译可通过,类型为Object,引用对象为Student
        System.out.println("============================");
        System.out.println(s1 instanceof Student);
        System.out.println(s1 instanceof Person);
        System.out.println(s1 instanceof Object);
        //System.out.println(s1 instanceof Teacher);
        //System.out.println(s1 instanceof String);
        //二者同级别,编译报错 Object>Person>Student  Object>String
        
    }
}

高转低需要使用类型转换
子类转父类可能丢失一些方法

posted on 2026-02-05 20:11  AAA神鹰  阅读(0)  评论(0)    收藏  举报