instanceof释义
instanceof用于判断一个对象是否是一个类的实例, 如:
boolean result = obj instanceof Class;
其中obj是对象,Class表示一个类或一个接口
obj为null时
System.out.println(null instanceof Object);//false
instanceof规则,当obj为null时,返回flase
子类与父类、接口间的比较
先准备四个类(接口)
interface Person{}
class Man implements Person{}
class Woman implements Person{}
class Worker extends Man{}
然后比较
public class Test
{
public static void main(String args[]){
Person pm = new Man();
Person pwm = new Woman();
Person pwo = new Worker();
Worker wor = new Worker();
//实现类与接口
System.out.println(pm instanceof Person);//true
//子类与父类
System.out.println(pwo instanceof Man);//true
//“隔代”实现类
System.out.println(pwo instanceof Person);//true
//没有继承关系
System.out.println(pwo instanceof Woman);//false
//没有向上转型的子类
System.out.println(wor instanceof Person);//true
//没有继承关系且没有向上转型
System.out.println(wor instanceof Woman);//编译报错
}
}
当obj不能转型成Class时,会编译报错
本文详细解析了Java中instanceof操作符的使用规则,包括其在对象实例判断、null值处理、子类与父类及接口间比较的应用。通过具体示例,展示了不同类型转换与比较时的运行结果与编译行为。
7254

被折叠的 条评论
为什么被折叠?



