instanceof运算符

// instanceof运算符:
//尽管null 对于每一个引用类型来说都是其子类型,但是instanceof 操作符被定义为在其左操作数为null
//时返回false。这被证明是实践中非常有用的行为。如果instanceof 告诉你一个对象引用是某个特定类
//型的实例,那么你就可以将其转型为该类型,并调用该类型的方法,而不用担心会抛出
//ClassCastException 或NullPointerException 异常。
//instanceof 操作符有这样的要求:如果两个操作数的类型都是类,其中一个必须是另一个的子类型。
//所以,new ArrayList() instanceof String是非法的。
String str = null;
System.out.println(str instanceof String);  
//编译错误:  
//System.out.println(new ArrayList() instanceof String); 

猜你喜欢

转载自jaesonchen.iteye.com/blog/2297876