why doesn't this code throw NullPointerException

大兔子大兔子 提交于 2019-12-01 02:59:41

It works because what matters is the compile-time type of the o field. The compiler will compile o.method() into the same byte code as One.method().

In particular, if you had a class Two that extends One, and both declare a static void method(), then

One x = new Two();
x.method(); // calls One.method(), not Two.method()

Good for obfuscation purposes, less good for maintainability...

method is static so it doesn't care about the One instance.

One o = null;
o.method();

Is the same as:

One.method();

static methods or variables are associated with class definition itself and not with the class instance. Hence your method() is available on o, but Ideally you should call it using the class name itself as:

     One.method();//static way of calling static methods

Because you declare static One o; outside the main function. You can try to declare it inside the main function, it cannot even be compiled...

Or you can declare it as One o = null in main, then it will be compiled but it's the same as One.method()

If you would have opened the code in your Development Environment e.g (Eclipse), instead of fooling people by showing the code here, which does provide code formating for static methods in italic style, then you would have seen that checkstyle claims about "Do not call a static method on an instance".

So it should be

One.method()

instead of

o.method()

Then it is clear why it does not crash!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!