Java学习笔记 第十三天 instanceof类型转换

 

 举例:Student和Teacher都继承Person。

package com.zhang.oop.Instanceof;

public class App {
    public static void main(String[] args) {
//      Object>Person>Student
//      Object>Person>Teacher
//      Person>String
// System.out.println(X instanceof Y)能不能编译通过?就取决于X与Y之间是否是继承关系。即子类和父类的关系
        Object s1 = new Student();
        System.out.println(s1 instanceof Object);//true
        System.out.println(s1 instanceof Person);//true
        System.out.println(s1 instanceof Student);//true
        System.out.println(s1 instanceof Teacher);//false
        System.out.println(s1 instanceof String);//false
        System.out.println("===================================");
        Person s2 = new Student();
        System.out.println(s2 instanceof Object);//true
        System.out.println(s2 instanceof Person);//true
        System.out.println(s2 instanceof Student);//true
        System.out.println(s2 instanceof Teacher);//false
        System.out.println("====================================");
        Student s3 = new Student();
        System.out.println(s3 instanceof Object);//true
        System.out.println(s3 instanceof Person);//true
        System.out.println(s3 instanceof Student);//true

    }
}


我们可以看到,只有new 的对象和 instanceof 比较的对象有继承关系时才能通过。

还有一种情况 都不在同一条线上 无法比较,如 Student 和 String、Student 和 Teacher。

 这会有点,总结一下

能否变异通过看x与y的类,如果存在子父关系或父子关系,则能编译通过。

若x与y不存在父子关系则不能通过如 Student 和 String、Student 和 Teacher。

编译过后T/F看引用指向对象,x指向的对象如果是后面y的子类,即是T反之为F。

类型之间的转化

之前我们在方法重写那遇到过,父类强制调用子类需要转化数据类型。父类为高等类 子类为低等类。

如下图 Student类里有个go();方法Person类中没有。

 Person类要调用Student类的方法失败

要想调用成功的把高类型装化为第类型。,

就是说父类用不了子类方法 就是把自己伪装成子类(类型转换)就可以用了。

总结

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

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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值