I've stumbled across some pretty weird code that I'm surprised doesn't 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 out 42! Can anyone explain?
References to static members of a class are resolved at compile-time. The compiler doesn't care what the value of the expression is, just its type, and so a ((WeirdCode) null).fooField
just resolves to WeirdCode.fooField
like anything else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With