引用变量的类型强转以及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

posted on 2014-07-21 11:15  欲上云端  阅读(640)  评论(0编辑  收藏  举报