Vru*_*ank 16 java nullpointerexception
public class Main
{
public static void main(String []ar)
{
A m = new A();
System.out.println(m.getNull().getValue());
}
}
class A
{
A getNull()
{
return null;
}
static int getValue()
{
return 1;
}
}
Run Code Online (Sandbox Code Playgroud)
我在SCJP书中遇到过这个问题.代码打印出来1而不是预期的NPE.有人可以解释相同的原因吗?
Jon*_*eet 22
基本上你正在调用静态方法,就像它是一个实例方法一样.这只是解决了静态方法调用,所以就像你写的那样:
A m = new A();
m.getNull();
System.out.println(A.getValue());
Run Code Online (Sandbox Code Playgroud)
IMO事实上你的代码是合法的,这是Java中的一个设计缺陷.它允许你编写非常误导性的代码,Thread.sleep作为一个我总是使用的例子:
Thread thread = new Thread(someRunnable);
thread.start();
thread.sleep(1000);
Run Code Online (Sandbox Code Playgroud)
哪个线程发送到睡眠状态?目前的"当然"......
静态方法调用在编译时解析.编译器看到它getNull()的返回值类型A有静态getValue()方法(并且没有相同名称的实例方法),所以在字节码中,实际的返回值getNull()被忽略并被A.getValue()调用.
| 归档时间: |
|
| 查看次数: |
370 次 |
| 最近记录: |