instanceof:判断一个对象跟某一个类有什么联系。
package com.jiemyx.oop.demo09;
public class Person {
}
package com.jiemyx.oop.demo09;
public class Student extends Person{
}
package com.jiemyx.oop.demo09;
public class Teacher extends Person{
}
package com.jiemyx.oop.demo09;
public class Application {
public static void main(String[] args) {
//Object > String
//Object > Person > Student
//Object > Person > Teacher
//System.out.println(x instanceof Y);
//对象x的引用类型 比如Student 与Y类存在继承关系,编译通过,
//然后判断实际类型 比如new Student() 是否跟Y类存在关系,存在关系true,不存在关系false
Student s = new Student();
System.out.println(s instanceof Object); //true
System.out.println(s instanceof Person); //true
System.out.println(s instanceof Student); //true
//System.out.println(s instanceof Teacher); //编译报错
//System.out.println(s instanceof String); //编译报错
System.out.println("===============");
Person p = new Student();
System.out.println(p instanceof Object); //true
System.out.println(p instanceof Person); //true
System.out.println(p instanceof Student); //true
System.out.println(p instanceof Teacher); //false
//System.out.println(p instanceof String); //编译报错
System.out.println("===============");
Object o = new Student();
System.out.println(o instanceof Object); //true
System.out.println(o instanceof Person); //true
System.out.println(o instanceof Student); //true
System.out.println(o instanceof Teacher); //false
System.out.println(o instanceof String); //false
}
}
运行结果:
true
true
true
===============
true
true
true
false
===============
true
true
true
false
false
原文:https://www.cnblogs.com/Jiemyx/p/14682616.html