instanceof用于判断某个对象是否属于某个类或者接口,若是的话就返回true,不是的话就返回false。
例:
Person类:
package com.dh.polymorphic;
public class Person {
}
Student类:继承Person类
package com.dh.polymorphic;
public class Student extends Person {
}
PersonInterface接口:
package com.dh.polymorphic;
public interface PersonInterface {
}
Teacher类:实现PersonInterface接口
package com.dh.polymorphic;
public class Teacher implements PersonInterface {
}
开始测试:
测试类:
package com.dh.polymorphic;
public class InstanceofTest {
public static void main(String[] args) {
//首先排列关系,别忘记了Object是所有类的鼻祖
//Object-->Person-->Student
//Object-->Teacher
// PersonInterface-->Teacher
Person person = new Person();
Student student = new Student();
Teacher teacher = new Teacher();
System.out.println(person instanceof Object); //true
System.out.println(person instanceof Person); //true
System.out.println(person instanceof Student); //false
System.out.println(person instanceof PersonInterface); //false
// System.out.println(person instanceof Teacher);
System.out.println(student instanceof Object); //true
System.out.println(student instanceof Person); //true
System.out.println(student instanceof Student); //true
System.out.println(student instanceof PersonInterface); //false
// System.out.println(student instanceof Teacher);
System.out.println(teacher instanceof Object); //true
System.out.println(teacher instanceof Teacher); //true
System.out.println(teacher instanceof PersonInterface); //true
// System.out.println(teacher instanceof Person);
// System.out.println(teacher instanceof Student);
}
}
总结:
原文:https://www.cnblogs.com/denghui-study/p/14313092.html