引用变量的类型强转以及InstanceOf方法的使用

引用到的类:
1 class Person{
2     String name;
3 }
4 class Student extends Person{
5     String sut_no;
6 }
7 class ClassMate extends Student{
8     
9 }
View Code
总结:使用instanceOf的时候注意 左边运行时类型是右边或其子类的类型(右边的实例) 返回true
    左边的编译类型必须是右边类型或其父类类型 (否则编译失败) 强制转换时并不是所有的父类都可以强转子类(编译都可以通过)只有满足父类的运行时类型是该类或该子类方可

public static void main(String[] args) throws Exception {
        String str = "test";
        System.out.println(str instanceof Object); //true
        Long number = new Long(123);
        System.out.println(number instanceof Object); //true
        
        //System.out.println(number instanceof String);  编译通不过
        Person p = new Person();
        Student s = new Student();
        System.out.println(s instanceof Person); //true
        
        Person stu = new Student();
        System.out.println(stu instanceof Person); //true
        System.out.println(stu instanceof Student); //true
        System.out.println(stu instanceof ClassMate); //false
        
        // java.lang.ClassCastException: Person cannot be cast to Student
        // 将父类强制转换为子类需要注意
        // 如果该父类的运行时类型是该类 或该子类 则可以
        // 否则会出现 ClassCastException
        // Person person = new Person();
        // Student student = (Student) person;
        
        Person person2 = new ClassMate();
        Student student2 = (Student)person2;
        
        System.out.println(student2 instanceof Person); //true
        System.out.println(student2 instanceof Student); //true
        //总结:使用instanceOf的时候右边类是 左边对象的运行时类型或者是运行时类型父类的时候返回true;
        //强制转换时并不是所有的父类都可以强转子类(编译都可以通过)只有满足父类的运行时类型是该类或该子类方可
    }

2、引用变量的强制类型转换

  引用类型之间的转换只能把一个父类变量转换成子类类型,如果两个没有任何继承关系的类型,则无法进行

  类型转换,否则编译时就会报错。如果试图将一个父类转换成子类,那么父类对象的运行时类型必须是子类

  的实例才行,否则在运行时引发ClassCastException;

3、所谓创建A类的实例:就是说这个实例是A类或其子类的对象 instanceOf的作用就是判断 左边对象运行时类型到底是不是 右边的实例 若是 返回true 否则false

转载于:https://www.cnblogs.com/Wen-yu-jing/p/3858031.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值