why doesn't this code throw NullPointerException

后端 未结 5 1314
攒了一身酷
攒了一身酷 2021-01-11 12:42

I was just discussing about calling static methods using class name with my friend and tried out this code and expected it to throw NPE at runtime.but as it turn out it dint

5条回答
  •  礼貌的吻别
    2021-01-11 13:46

    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...

提交回复
热议问题