instanceof

本文通过示例展示了Java中类继承的概念,以及`instanceof`关键字如何检查对象的类型。我们创建了Person类,然后Teacher和Student类分别继承Person。在主函数中,我们使用`instanceof`检查不同类型的引用,揭示了Java类型系统中的父子关系。
摘要由CSDN通过智能技术生成

Person类:

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

Teacher类继承Person类:

public class Teacher extends Person {
}

Student类继承Person类:

public class Student extends Person {
}

主函数:

Object object = new Student();
System.out.println(object instanceof Student);
System.out.println(object instanceof Person);
System.out.println(object instanceof Teacher);
System.out.println(object instanceof Object);
System.out.println(object instanceof String);

运行结果:
在这里插入图片描述
主函数:

Person person = new Student();
System.out.println(person instanceof Student);
System.out.println(person instanceof Person);
System.out.println(person instanceof Object);
System.out.println(person instanceof Teacher);
//System.out.println(person instanceof String);//编译报错

运行结果:

在这里插入图片描述
主函数:

Student student = new Student();
System.out.println(student instanceof Student);
System.out.println(student instanceof Person);
System.out.println(student instanceof Object);
//System.out.println(student instanceof Teacher);//编译报错
//System.out.println(person instanceof String);//编译报错

运行结果:
在这里插入图片描述

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

instanceof用来判断两个类型之间是否存在父子关系
父转子需强制转换,子转父可能会丢失方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱与意志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值