zoukankan      html  css  js  c++  java
  • 多态中的引用类型转换

    多态的引用类型转换:
    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 }
  • 相关阅读:
    codevs 1432 总数统计
    codevs3500 快速幂入门题解
    #163. 【清华集训2015】新式计算机
    2989:糖果
    191:钉子和小球
    java 删除所有HTML工具类
    DateTools时间插件
    新的开始
    springBoot---端口,路径数据配置
    springBoot---多个配置文件读取
  • 原文地址:https://www.cnblogs.com/100thMountain/p/5401741.html
Copyright © 2011-2022 走看看