System.out.println(x instanceof y);
能不能编译通过
查看x和y有没有继承关系
继承关系
//object>String
//object>>Person>Teacher
//object>Person>Student
Object ob=new Student();
System.out.println(ob instanceof Student);//true
System.out.println(ob instanceof Person);//true
System.out.println(ob instanceof Object);//true
System.out.println(ob instanceof Teacher);//false
System.out.println(ob instanceof String);//false
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);//编译报错
Student s =new Student();
System.out.println(s instanceof Student);//true
System.out.println(s instanceof Person);//true
System.out.println(s instanceof Object);//true
// System.out.println(s instanceof Teacher);//编译报错
// System.out.println(s instanceof String);//编译报错
本文详细介绍了Java中`instanceof`关键字的使用,通过实例展示了如何检查对象是否为某个类或其子类的实例。示例代码演示了不同继承关系下`instanceof`的返回结果,包括对象、子类、父类和不相关类之间的关系,帮助理解Java类型的层次结构和继承检查。
962

被折叠的 条评论
为什么被折叠?



