zoukankan      html  css  js  c++  java
  • 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语句配合使用

  • 相关阅读:
    LeeCode-Invert Binary Tree
    LeeCode-Contains Duplicate
    LeeCode-Linked List Cycle
    LeeCode-Number of 1 Bits
    LeeCode-Delete Node in a Linked List
    LeeCode-Same Tree
    LeeCode-String to Integer (atoi)
    单链表复习
    POJ1258 (最小生成树prim)
    HDU1248 (完全背包简单变形)
  • 原文地址:https://www.cnblogs.com/chenyuan7/p/8025706.html
Copyright © 2011-2022 走看看