Java基础笔记30——向上转型和向下转型

1.上溯造型:子类 -> 父类,自动转换
前提:基于继承关系
注意:转换过程,会失去子类原来的属性与方法,仅能使用父类的属性与方法

2.下溯造型:父类 -> 子类,强制转换
前提:基于继承关系
注意:曾经向上转换过的对象,才能在向下转换,对象不允许不经过上溯造型而直接下溯造型

3.instanceof运算符:用于检测对象是否是一个特定类型
规则
对象 instanceof 类/接口类型

 

package com.lqh.chapter03;

public class _28upanddown {
    public static void main(String[] args) {
        // 上溯造型:子类转父类

        // 子类
        SuperMan ironMan = new SuperMan();
        ironMan.fly();
        // 父类
        Man man = ironMan;
        man.walk();
        // man.fly();//此时ironMan的fly方法损失了,无法使用

        // 下溯造型:父类转子类
        SuperMan ironMan2 = (SuperMan) man;
        ironMan2.fly();
        
        /*对象不允许不经过上诉造型而直接下溯造型
         *  java.lang.ClassCastException: Man cannot be cast to SuperMan 
         */
        //父类
        Man lqh = new Man();
        lqh.say();
        //子类
        /*
         * SuperMan spider = (SuperMan) lqh; spider.fly();
         */
        
        /*
         * 子类与子类之间不允许转换
        */
        //子类
        NormalMan normalman = new NormalMan();
        //子类
        //SuperMan antMan = (SuperMan) normalman;
        
        System.out.println(ironMan instanceof Man);//true
        System.out.println(ironMan instanceof SuperMan);//true
        
        //System.out.println(ironMan instanceof NormalMan);//false
    }
}

输出结果为:

超人:飞
人:走路
超人:飞
人:说话
true
true

posted @ 2021-09-17 17:54  `青红造了个白`  阅读(30)  评论(0编辑  收藏  举报