Since the fubar field fubar declared static , there is only one field anywhere that is actually called Foo.fubar . Each instance of Foo shares this copy. When you access this field from a Foo object, Java does not try to reference the object to find it. Instead, it searches for an object in a specially defined place that can be accessed regardless of any link. Therefore, if you try to find this field of a null object, you can do this without raising any NullPointerException , since the object is never referenced.
EDIT : Bytecode is definitely fine! Given this source file:
public class Foo { static int fubar; public Foo() { ((Foo)null).fubar = 137; } }
The bytecode is generated here:
0: aload_0 1: invokespecial #1; //Method Object."<init>":()V 4: aconst_null 5: checkcast #2; //class Foo 8: pop 9: sipush 137 12: putstatic #3; //Field fubar:I 15: return
Note that line 12 uses the putstatic , which stores the value in the static field. It does not refer to a recipient object of any type. In fact, if you notice that the generated bytecode (lines 4-8) performs a null to Foo listing, but then immediately pops up the op code to pull it out of the stack. He never referenced anywhere in the bytecode.
templatetypedef
source share