关于引用类型转换

package com.imooc.animal;


/**
 * java中引用类型的转换
 * 1,自动类型提升 ,向上类型转换
 * 2,强制类型转换,向下类型转换
 * 注意:为了避免强制类型转换所带来的安全问题,
 *        可以使用关键字instanceof,通常也会配合上使用if语句
 * */
public class Test {


public static void main(String[] args) {
Dog dog =new Dog();//创建子类对象,让子类对象的引用指向子类对象
Animal animal =dog;//自动类型提升,向下类型提升,将子类的引用赋值给父类的引用
if(animal instanceof Dog){
Dog dog2=(Dog)animal;//强制类型转换,向下类型提升,将父类的引用赋值给子类的引用
}
else{
System.out.println("抱歉无法转换为Dog类型的引用");
}

/*强制类型转换的时候会出现安全隐患
* 将指向狗的引用赋值给猫类型的引用
* Exception in thread "main" java.lang.ClassCastException: com.imooc.animal.Dog cannot be cast to com.imooc.animal.Cat
at com.imooc.animal.Test.main(Test.java:20)
为了解决这个问题,在进行强制类型转换的时候,可以使用instanceof关键字进行判断
* */
if(animal instanceof Cat){
Cat cat=(Cat)animal;//编译时按照 Cat类型,但是运行的时候用的是Dog类型
}
else{
System.out.println("抱歉无法转换为Cat类型引用");
}
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值