null 和 instanceof

1 instanceof 操作符定义为当左操作符为null的时候返回false.  右操作符不能是null;

   JSL 15.2如果两个操作数的类型都是类,其中一个必须是另一个的子类型;

 

package arkblue.lang;

public class TypeInstanceTest {
	public static void main(String[] args) {
		String s = null;
		System.out.println(s instanceof Object); // false

		System.out.println(s instanceof String); // false

		// 下面的不能通过编译 Incompatible conditional operand types String and String[]
		// boolean as = (s instanceof String[]);

		// 不能编译 Syntax error on token "null", invalid ReferenceType
		// System.out.println(s instanceof null);

		// 不能编译 Incompatible conditional operand types TypeInstanceTest and
		// String
		// System.out.println(new TypeInstanceTest() instanceof String);

		System.out.println(new String() instanceof String);  //true

		System.out.println(new String() instanceof Object); //true

		//
		TypeInstanceTest test = (TypeInstanceTest) new Object();
	}
}

 

 

结果

false
false
true
true
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to arkblue.lang.TypeInstanceTest
	at arkblue.lang.TypeInstanceTest.main(TypeInstanceTest.java:25)

 

 

2 访问静态方法,使用表达式作为限定符。表达式的值所引用的对象的运行期类型在确定哪一个方法被调用的时候不起作用,而且对象有标识符,其标识符也不起任何作用。

 

package arkblue.lang.javapuzzler.n54;

public class Null {
	public static void greet() {
		System.out.println("Hello World!");
	}

	public static void main(String[] args) {
		((Null) null).greet();
	}
}

 

结果

 

Hello World!

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值