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类型引用");
}
}
}
/**
* 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类型引用");
}
}
}