Strange code output

I came across some rather strange code that surprises me, does not cause an error

public class WeirdCode { public static int fooField = 42; public WeirdCode getFoo(){ return null; } public static void main(String args[]) { WeirdCode foo = new WeirdCode(); System.out.println(foo.getFoo().fooField); } } 

Surprisingly, it prints 42! Can someone explain?

+5
source share
1 answer

References to static class members are resolved at compile time. The compiler does not care what the value of the expression is, just its type, and therefore ((WeirdCode) null).fooField just solves WeirdCode.fooField like everything else.

+13
source

All Articles