Person类:
public class Person {
public void go(){
System.out.println("go");
}
}
Teacher类继承Person类:
public class Teacher extends Person {
}
Student类继承Person类:
public class Student extends Person {
}
主函数:
Object object = new Student();
System.out.println(object instanceof Student);
System.out.println(object instanceof Person);
System.out.println(object instanceof Teacher);
System.out.println(object instanceof Object);
System.out.println(object instanceof String);
运行结果:
主函数:
Person person = new Student();
System.out.println(person instanceof Student);
System.out.println(person instanceof Person);
System.out.println(person instanceof Object);
System.out.println(person instanceof Teacher);
//System.out.println(person instanceof String);//编译报错
运行结果:
主函数:
Student student = new Student();
System.out.println(student instanceof Student);
System.out.println(student instanceof Person);
System.out.println(student instanceof Object);
//System.out.println(student instanceof Teacher);//编译报错
//System.out.println(person instanceof String);//编译报错
运行结果:
Object > String
Object > Person > Teacher
Object > Person > Student
instanceof用来判断两个类型之间是否存在父子关系
父转子需强制转换,子转父可能会丢失方法