zoukankan      html  css  js  c++  java
  • 向上转型与向下转型

    向上转型与向下转型是适用于“父子类”之间。

    1、向上转型:当把子类的对象赋值给父类的变量时,编译期间会发生自动类型提升。

    2、向下转型:当把父类的变量的值重新赋值给一个子类的变量时,需要强制类型转换。

    向下转型有风险:可能会发生ClassCastException类型转换异常。

    向下转型要成功:当这个父类的变量中存储的实际的对象类型 <= 强制转换的子类类型。

    class Person{
        //...
    }
    class Woman extends {
        //..
    }
    class ChineseWoman extends Woman{
        //..
    }
    
    Person p1 = new Person();
    Person p2 = new Woman();
    Person p3 = new ChineseWoman();
    
    Woman w1 = (Woman)p1;//错误
    Woman w2 = (Woman)p2;//可以
    Woman w3 = (Woman)p3;//可以
    

      

    3、关键字:instanceof

    它用于判断xx是否是谁的实例对象。

    变量/对象  instanceof 类型

    上面的表达式运算结果是true/false.

    class Person{
        //...
    }
    class Woman extends {
        //..
    }
    class ChineseWoman extends Woman{
        //..
    }
    
    Person p1 = new Person();
    Person p2 = new Woman();
    Person p3 = new ChineseWoman();
    
    System.out.println(p1 instanceof Woman);//false
    System.out.println(p2 instanceof Woman);//true
    System.out.println(p3 instanceof Woman);//true
    

      

  • 相关阅读:
    Python多线程_thread和Threading
    Python多线程_thread和Threading
    ICMP协议
    ICMP协议
    Python中的Pexpect模块的简单使用
    Python中的Pexpect模块的简单使用
    Python中math和cmath模块的使用
    Python中math和cmath模块的使用
    Python中sys模块的使用
    Python模块化编程
  • 原文地址:https://www.cnblogs.com/panyizuoshan/p/11454676.html
Copyright © 2011-2022 走看看