多态中的引用类型转换

多态的引用类型转换:
1.向上类型转换(隐式/自动类型转换),是小类型到大类型的转换 无风险
2.向下类型转换(强制类型转换),是大类型到小类型 有风险,可能会发生溢出
3. instanceof运算符,来解决引用对象的类型,避免 类型转换的安全性问题

 1 package com.imooc;
 2 
 3 public class Initial {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
17         
18         /***多态中的引用类型转换***/
19         Dog dog = new Dog();
20         Animal animal = dog;   //自动类型提升  向上类型转换
21         //Dog dog2 = animal;   //父类类型对象不能转换为子类对象
22         if(animal instanceof Dog){
23             Dog dog2 = (Dog)animal;   //强制类型转换  向下类型转换
24         }else{
25             System.out.println("无法进行类型转换  Dog类型");
26         }        
27         
28         //Cat cat = (Cat)animal;    //1.编译时  按Cat类型  2.运行时  Dog类型
29         if(animal instanceof Cat){
30             Cat cat = (Cat)animal;
31         }else{
32             System.out.println("无法进行类型转换  Cat类型");
33         }
34     }
35 
36 }
原文地址:https://www.cnblogs.com/100thMountain/p/5401741.html