Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't this code throw NullPointerException

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. i just want to understand the execution order.

public class One {

    public static void method() {
        System.out.println("in static one");
    }
}

public class Two {

    static One o;

    public static void main(String[] args) {
        o.method(); // expected NPE here, as o is null
    }
}

I know that static methods should be invoked with their class name, I even know that IDE's would give a compiler warning when we call static methods with an instance. but we could also call them by creating an instance, however, i never created an instance here, o should get its default value null, thus calling o.method() should throw an NPE at run time, but it doesn't. can you guys please shed some light on how the execution order is in this code.

like image 885
PermGenError Avatar asked Dec 06 '12 21:12

PermGenError


1 Answers

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

like image 168
Ian Roberts Avatar answered Sep 23 '22 10:09

Ian Roberts