1、只能在继承层次内进行类型转换 。
2、在将超类转换成子类之前 , 应该使用instanceof 进行检查。
Person 为父类, Man为子类
public static strictfp void main(String[] args) {
//编译看左边,运行看右边, p 其实是Man对象
Person p = new Man();
if(p instanceof Man){
System.out.println(p.getClass().getSimpleName());
System.out.println("类型转换成功");
p = (Man)p;
}else{
System.out.println("类型转换失败");
}
}
结果:
3、null instanceof Man
不会产生异常 , 只是返回 false,null没有引用任何对象,当然也不会引用Man对象。