A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 丁朋伟 黑马帝   /  2011-9-19 16:41  /  6313 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

今天复习了笔记发现instanceof一个比较容易犯错的地方,分享与大家学习
instanceof的作用是测试它左边的对象是否是它右边的类的实例

                Object hello = "hello";
                System.out.println(hello instanceof Object);
                System.out.println(hello instanceof String);
                System.out.println(hello instanceof Comparable);
                System.out.println(hello instanceof Math);
               
                String string = "hello";
                //System.out.println(string instanceof Math);
                System.out.println(string instanceof java.io.Serializable);
上面打印结果是
true
true
true
false
true
而System.out.println(string instanceof Math);就不能通过编译
查资料发现instanceof使用的时候是有限制的
只有一下三种情况才能通过编译
1.instanceof前面的类型与后面的类型相同
2.instanceof前面的类型是后面的类型父类
3.instanceof前面的类型是后面的类型子类
如果前一个类型与后面的类型无关就不能通过编译

在运行时也要注意一个情况
                Object hello = "hello";
                Math math = (Math)hello;
                System.out.println(math instanceof Object);
这个能通过编译却在运行时引发"java.lang.ClassCastException:
这在运行时要求被转型的变量所引用的对象实际类型是目标类型的实例或是目标类的子类或是实现类的实例

因此可以得出一个能把字符串避开" java.lang.ClassCastException:或是java.lang.NullPointerException的一个方法
        String string = null;
       string instanceof String
返回false
        if(string instanceof String){
        }else{      
        }

2 个回复

倒序浏览
黑马网友  发表于 2011-9-19 16:48:21
沙发

回复 楼主 的帖子

学习了,谢谢楼主分享。
回复 使用道具 举报
黑马网友  发表于 2011-9-19 16:48:48
藤椅
顶楼主!我也把自己的总结拿出来给大家分享下:
Example:    Class Teacher and Student are subclass of class Person.
    Person p;
    Teacher t;
    Student s;
    p, t and s are all non-null.
    if(t instanceof Person) {  s = (Student)t; }
What is the result of this sentence?
A. It will construct a Student object.
B. The expression is legal.
C. It is illegal at compilation.
D. It is legal at compilation but possible illegal at runtime.
     instanceof操作符的作用是判断一个变量是否是右操作数指出的类的一个对象,由于java语言的多态性使得可以用一个子类的实例赋值给一个父类的变量,而在一些情况下需要判断变量到底是一个什么类型的对象,这时就可以使用instanceof了。当左操作数是右操作数指出的类的实例或者是子类的实例时都返回真,如果是将一个子类的实例赋值给一个父类的变量,用instanceof判断该变量是否是子类的一个实例时也将返回真。此题中的if语句的判断没有问题,而且将返回真,但是后面的类型转换是非法的,因为t是一个Teacher对象,它不能被强制转换为一个Student对象,即使这两个类有共同的父类。如果是将t转换为一个Person对象则可以,而且不需要强制转换。这个错误在编译时就可以发现,因此编译不能通过。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马