instanceof
A(对象) instcnaceof B(类)结果为boolean型
A和B比较之前会先判断A能不能转换成B类型,能则通过,不能则编译报错
编译通过后会把A和B比较,如果A是B本类或者子类的对象,结果就是true,反之就是flase
如
先创建三个类,其中Person是Student和Teacher的父类
public class Person {
}
public class Student extends Person {
}
public class Teacher extends Person {
}
//Object > Person > Student
//Object > String
//Object > Person > Teacher
以下是比较及结果:
Object object = new Student();
System.out.println(object instanceof Student);//true
System.out.println(object instanceof Person);//true
System.out.println(object instanceof Object);//true
System.out.println(object instanceof Teacher);//false
System.out.println(object instanceof String);//false || object instanceof String中object是Object类型,String是Object的子类也继承了Object类型,所有能类型转换,编译通过
===============================================
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);//编译报错! || person instanceof String之所以编译会报错是因为person是Person类型,而String是final类型,两者不能转换
================================================
Student student = new Student();
System.out.println(student instanceof Student);//true
System.out.println(student instanceof Person);//true
System.out.println(student instanceof Object);//true
//System.out.println(student instanceof Teacher);//编译报错!
//System.out.println(student instanceof String);//编译报错!