13 instanceof 和类型转换

instanceof 和类型转换

package com.zhan.base05Oop.base05Oop04;

public class Test13 {


    // 编译看左,运行看右!!!!!!

    /*
    1.父类的引用指向子类的对象: 即声明的是父类,实际上指向的是子类的一个对象(面向接口编程)

    2. 把子类转换为父类,向上转型:自动转换
       把父类转换为子类,向下转型:强制转换

    3. 方便方法的调用,减少重复的代码

    Java是一门抽象的语言
    封装,继承,多态,抽象类,接口
     */

    // instanceof  用来判断 对象和类是否又联系
    /*
    instance of
英 [ˈɪnstəns ɒv]   美 [ˈɪnstəns əv]
实例;某描述符的实例;间的关系;描述符的实例
     */

    public static void main(String[] args) {
        // 类型转换

        //  高            低
        // Person person=new Student();

        Student student1=new Student();
        Person person1=student1;      // 低转高,自动转换

        Person person2=new Person();
        Student student2=(Student) person2;   // 高转低,需要强制转换

        // person1.testS(); 编译错误(编译看左),将子类转换为父类后,可能执行不了原本的一些方法
        student2.testH();  // 将父类转换为子类后,没问题

    }
}

class Person{
    public void testH(){
        System.out.println("HHH");
    }
}

class Student extends Person{
    public void testS(){
        System.out.println("SSS");
    }
}

class Tescher extends Person{

}

/*
       Object object = new Student();
        Person person = new Student();
        Student student = new Student();

        // Object>Person>Student / Teacher
        // Object>String

        //System.out.println(x instanceof y); 能不能编译通过,来判断 x 和 y 之间是否存在继承关系(直系才能通过编译)

        System.out.println(object instanceof Student);   // true
        System.out.println(object instanceof Person); // true
        System.out.println(object instanceof Object); // true
        System.out.println(object instanceof Tescher); // false
        System.out.println(object instanceof String);  // false

        System.out.println("====================================================");
        System.out.println(person instanceof Student);   // true
        System.out.println(person instanceof Person); // true
        System.out.println(person instanceof Object); // true
        System.out.println(person instanceof Tescher);  // false      // 编译看左,运行看右!!!!!!
      // System.out.println(person instanceof String);  // 编译就已经报错,因为 Person 和 String 毫无联系
        System.out.println("=======================================================");

        System.out.println(student instanceof Student);   // true
        System.out.println(student instanceof Person); // true
        System.out.println(student instanceof Object); // true
        //System.out.println(student instanceof Tescher); // 编译就已经报错,因为 Student 和 String 毫无联系
        //System.out.println(student instanceof String);  // 编译就已经报错,因为 Student 和 String 毫无联系
 */
posted @   被占用的小海海  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示