instanceof关键字
instanceof
-
用于判断一个对象是什么类型的(判断有没有类的继承关系)
public class Person { public void run() { System.out.println("run"); } }
public class Student extends Person{ //重写了父类的run public void run() { System.out.println("student run"); } public void eat() { System.out.println("eat"); } }
public class Teacher2 extends Person{ void print() { System.out.println("teacher"); } }
public class Demo { static public void main(String[] args) { //x instanceof Y能不能编译通过看两者有没有关系,是ture就有继承关系,是false就同级 //Object>Person>Student //Object>Person>Teacher //Object>String Object s1=new Student(); System.out.println(s1 instanceof Object); //有继承关系,输出true System.out.println(s1 instanceof Person); //有继承关系,输出true System.out.println(s1 instanceof Student); //有继承关系,输出true System.out.println(s1 instanceof String); //有继承关系,输出true System.out.println(s1 instanceof Teacher); //有继承关系,输出true Person s2=new Student(); System.out.println(s2 instanceof Object); //有继承关系,输出true System.out.println(s2 instanceof Person); //有继承关系,输出true System.out.println(s2 instanceof Student); //有继承关系,输出true System.out.println(s2 instanceof Teacher2); //student和teacher同级 输出false // System.out.println(s2 instanceof String); //编译报错,没有关联 System.out.println(); Student s3=new Student(); System.out.println(s3 instanceof Object); //有继承关系,输出true System.out.println(s3 instanceof Person); //有继承关系,输出true System.out.println(s3 instanceof Student); //有继承关系,输出true // System.out.println(s3 instanceof String); //无关 编译报错 // System.out.println(s3 instanceof Teacher2); //无关 编译报错 } }