Uninitialized variables and members in Java
The language defines it this way.
Instance variables of object type default to being initialized to null. Local variables of object type are not initialized by default and it's a compile time error to access an undefined variable.
See section 4.12.5 for SE7 (same section still as of SE14) http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5
Here's the deal. When you call
TestClass tc = new TestClass();
the new
command performs four important tasks:
- Allocates memory on the heap for the new object.
- Initiates the class fields to their default values (numerics to 0, boolean to
false
, objects tonull
). - Calls the constructor (which may re-initiate the fields, or may not).
- Returns a reference to the new object.
So your fields 'a' and 'b' are both initiated to null
, and 'a' is re-initiated in the constructor. This process is not relevant for method calling, so local variable 'c' is never initialized.
HTH
PS: for the gravely insomniac, read this.
The rules for definite assignment are quite difficult (read chapter 16 of JLS 3rd Ed). It's not practical to enforce definite assignment on fields. As it stands, it's even possible to observe final fields before they are initialised.