Java类的类型转换和instanceof关键字

  • 关键点都在代码注释中
package oop.demo06;
public class Application {
    public static void main(String[] args) {

        //左侧的实际类型决定了编译是否成功,即左侧的实际类型用于判断一个实例在哪条继承线上
        //右侧的指向类型决定了返回结果,即右侧的指向类型是判断一个实例在一个确定的继承线中是否有继承关系

        //通式:X instanceof Y  //能不能编译通过看X的实际类型

        //object > string
        //object > person > student
        //object > person > teacher

        Object student = 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); //false
        System.out.println( student instanceof String); //false

        System.out.println("==========================");
        Person person = new Student();
        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("=========================");
        Student student1 = new Student();
        System.out.println( student1 instanceof Student); //true
        System.out.println( student1 instanceof Person); //true
        System.out.println( student1 instanceof Object); //true
        //System.out.println( student1 instanceof Teacher); //编译报错
     //=============================================================
        //类型之间的转换:基本类型转换满足高低
        //这里说的转换时
        //高                   低
        Person student2 = new Student();
        //子类转换为父类可能丢失一些本来的方法
        //student2.eat(); 无法执行,因为Person类中没有eat方法
        //将这个转换为student就可以使用student类型的方法,即强行转化成Student类
        ((Student)student2).eat();

        /*
        1.必须是父类引用指向子类
        2.把子类转换为父类是向上转型,可能会丢失一些方法
        3.把父类转换为子类是向下转型,需要强制转换
        4.方便了方法的调用
         */
    }
}
//结果
true
true
true
false
false
==========================
true
true
true
false
=========================
true
true
true
eat
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值