instanceof运算符

一. 强制转换有风险

public class Test{
    public static void main(String[] args){
        Animal a = new Bird();
        Animal b = new Cat();
        
        Cat x = (Cat)a;
		x.doingSth(); 
        
        Cat y = (Cat)b;
		y.doingSth();
    }
}

class Animal{
    
}

class Cat extends Animal{
    public void doingSth(){
		 System.out.println("猫儿在走路");
	}
}

class Bird extends Animal{
    	public void doingSth(){
		 System.out.println("鸟儿在飞翔");
	}
}

报错

java.lang.ClassCastException类型转换异常

二. 编译没有问题, 运行阶段出现问题

​ 如上Cat x = (Cat)a;出现问题,

编译时, 编译器检测到a这个引用是Animal类型, 而Animal和Cat之间存在继承关系,所以可以向下转型。

运行时, 堆内存实际创建的对象时: Bird对象。运行时将Bird对象转换成Cat对象, 不可以,两者没有继承关系。

三. 用instanceof运算符可以很好的避免这样的错误

  • instanceof可以在运行阶段动态判断引用指向的对象的类型

  • 语法:引用 instanceof 类型

  • 返回结果为:true/false

    所以可将主方法修改为:

public class Test{
    public static void main(String[] args){
        Animal a = new Bird();
        Animal b = new Cat();
        
		System.out.println(a instanceof Cat);
		if(a instanceof Cat){
			Cat x = (Cat)a;
			x.doingSth();
		}	

		System.out.println(b instanceof Cat);
		if(b instanceof Cat){
			Cat y = (Cat)b;
			y.doingSth();
		}
    }
}

结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值