• instanceof 与 应用类型强转


    package com.moxi.wc;
    
    /**
     * @author Mr.Wang
     * @version 1.0
     * @since 1.8
     */
    public class Instan {
        // 一个关键词instanceof
        public static void main(String[] args) {
            System.out.println(null instanceof Object); // null instanceof xxx 都是false
            // 以下有几个类关系如下
            // Object => Student      Object => Personer   Object => String  Personer => Student
            // 第一种情况
            Student s = new Student();
            System.out.println(s instanceof Object);
            System.out.println(s instanceof Personer);
            System.out.println(s instanceof Student);
            /*System.out.println(s instanceof String);*/ // 编译就报错Student类类型和String没有关系
            // 第二种情况
            Personer per = new Personer();
            System.out.println(per instanceof Object);
            System.out.println(per instanceof Personer);
            System.out.println(per instanceof Student);  // false 因为per不是Student或Student子类的实例
    
            // 第三种情况
            Personer per2 = new Student(); // 结果和类型是Student一样
            System.out.println(per2 instanceof Object);
            System.out.println(per2 instanceof Personer);
            System.out.println(per2 instanceof Student);  // true
        // 总结: instanceof 左边是引用类型右边是类,true: 说明该实例是右边本身或者子类实例出来的,和什么类型没有关系(第三种)
        // 毫无关系的编译就会报错
    
        // ====================================>
        // 为了方便类型转换父类引用指向子类就是一种低转高的例子,代价是子类特有的方法和属性不能被调用
        // 父类向子类转化必须是强转((Student) Personer).子类的方法
        ((Student)per).keyboards();  // 报错不能强制转换,因为实例不一样,所以强转之前用instanceof是个明智的选择
        ((Student)per2).keyboards(); // 正常运行 (先姑且Personer类和Student类都有且是父子关系)
        }
    
    }
    你的努力有资格到拼天赋的程度吗?
  • 相关阅读:
    测试项目框架搭建
    项目实战(一)
    接口和HTTP协议(二)
    接口和http协议(一)
    什么是DFX测试
    完美解决安装在虚拟机中的CentOS7无法联网的问题
    RIP动态路由协议
    ensp实验--------RIP动态路由实验
    ensp实验--------telnet登录认证
    CSMA/CD协议
  • 原文地址:https://www.cnblogs.com/wchjdnh/p/14406266.html
Copyright © 2020-2023  润新知