instanceof和类型转换

instanceof和类型转换

instanceof 判断一个对象是否是一个类的实例

编译不报错前提:两个类之间存在关系

核心父类引用指向子类对象

父类转子类 是引用类型的从高转低,需要强制转换

子类转父类,可能丢失一些自己本来的方法

代码示例 需认真理解

Person.java

package com.example.oop.demo03;

public class Person {
    public String name;

    public void say() {
        System.out.println("person说了一句话");
    }

    public static void eat() {
        System.out.println("person吃了一口饭");
    }

    public void run() {
        System.out.println("person run");
    }
}

Person.java

package com.example.oop.demo03;

public class Student extends Person {
    public String name;
    public String grade;

    @Override
    public void say() {
        System.out.println("student说了一句话");
    }

    public static void eat() {
        System.out.println("student吃了一口饭");
    }
}

Teacher.java

package com.example.oop.demo03;

public class Teacher extends Person {
}

Application.java

package com.example.oop;

import com.example.oop.demo03.Person;
import com.example.oop.demo03.Student;
import com.example.oop.demo03.Teacher;

public class Application {
    // 一个工程只有一个main方法
    public static void main(String[] args) {
        // 静态方法调用等式左边的类型,非静态方法调用看等式右边的类型
        Student student = new Student();
        Person person = new Student(); //父类引用指向子类对象
        Object object = new Student();

        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 Teacher);// 编译错误
//        System.out.println(student instanceof String);// 编译错误

        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 Teacher);// false
//        System.out.println(person instanceof String);// 编译错误

        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 Teacher);// false
        System.out.println(object instanceof String);// false

    }
}
posted @   Oh,mydream!  阅读(26)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示