Java 多态中的引用类型转换

向上类型转换,也叫隐士/自动类型转换,不存在风险

向下类型转换,也叫强制类型转换,存在风险

class Ex17{

  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("无法转换");

  }

      if(animal instanceof Cat){    //animal对象能否转换为Cat类型

        Cat cat=(Cat)animal;  //编译时,Cat类型    运行时,Dog类型(会报错),此时可用instanceof避免类型转换的安全性问题

    }else{

        System.out.println("无法转换");

  }

}

}

instanceof可判断一个引用是否是某个类型,或者是某个类型的子类型,它会返回一个值,通常会用这个值与if语句配合使用

原文地址:https://www.cnblogs.com/chenyuan7/p/8025706.html