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类都有且是父子关系)
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章