Last active
April 16, 2016 10:03
-
-
Save exceptionplayer/09b27b89fc722a8b313decad8cb496be to your computer and use it in GitHub Desktop.
Java容易迷惑的代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NULL { | |
public static void haha() { | |
System.out.println("haha"); | |
} | |
public static void main(String[] args) { | |
((NULL)null).haha(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
输出为haha,因为null值可以强制转换为任何java类类型,(String)null也是合法的。但null强制转换后是无效对象,其返回值还是为null,而static方法的调用是和类名绑定的,不借助对象进行访问所以能正确输出。
反过来,没有static修饰就只能用对象进行访问,使用null调用对象肯定会报空指针错了。这里和C++很类似。