Java学习第十六天 Instanceof和类型转换

instanceof 的作用就是判断一个对象是什么类型。

直接看代码:

Application(主类):

public class Application {
    public static void main(String[] args) {
//      Object>Person>Student
//      Object>Person>Teacher
//      Person>String
        Object student = new Student();
        System.out.println(student instanceof Object);//true
        System.out.println(student instanceof Person);//true
        System.out.println(student instanceof Student);//true
        System.out.println(student instanceof Teacher);//false
        System.out.println(student instanceof String);//false
        System.out.println("===================================");
        Person person = new Student();
        System.out.println(person instanceof Object);//true
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Student);//true
        System.out.println(person instanceof Teacher);//false
        System.out.println("====================================");
        Student student1 = new Student();
        System.out.println(student1 instanceof Object);//true
        System.out.println(student1 instanceof Person);//true
        System.out.println(student1 instanceof Student);//true

        //System.out.println(X instanceof Y)能不能编译通过?就取决于X与Y之间是否是继承关系。即子类和父类的关系

    }
}

Person类(父类)、Student(子类)、Teacher(子类);

它们之间的继承关系:

Object>Person>Student
Object>Person>Teacher 

运行结果:

如果子类和父类没有继承关系,则无法比较:

比如说Student和Teacher:

 

在Java的多态关系中,父类是无法调用子类独有的方法的,这个时候就需要进行类型转换:

直接看代码:

 Application(主类):

package com.oop.demo08;

public class Application {
    public static void main(String[] args) {

//        类型之间的转换   要有继承的关系才可以进行转换
//        高-------->低   强制类型转换
        Person person = new Student();
//        Student person1 = (Student) person;
//        person1.run();
        ((Student)person).run();
        Student student = new Student();
        student.run();
        Object object = student;

    }

}

把子类转换为父类:向上转型,直接转(低--------->高)

把父类转换为则子类:向上转型,强制转换(高--------->低)

和之前的数据类型转换差不多。

注意:子类向上转型时,有时会丢失方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

芝麻干

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

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

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

打赏作者

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

抵扣说明:

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

余额充值