4.2 Reading, Writing & Initializing Object Fields
Key Takeaways
Instance fields are read and written through a live object reference with dot notation (obj.field), whereas static fields belong to the class and are accessed via ClassName.field
Reading or writing an instance field on a null reference throws NullPointerException at runtime, but accessing a static field through a null typed reference (RefType r = null; r.staticField) compiles and succeeds without throwing NullPointerException
For a first active use of an ordinary subclass, the superclass’s static initializer code runs before the subclass’s. Instance initialization proceeds from the superclass to the subclass for each successful construction.
Ordinary static and instance initializers run in textual order at their respective initialization stages. Static constant variables have special initialization rules.
A same-class field initializer cannot read a later field of the same kind by simple name. A simple assignment to a later field or a qualified access can compile.
Dot Notation: Instance Fields vs. static Fields
In Java, you read and write an object's accessible fields using the dot operator (.):
- Instance fields exist separately inside every object created with
new. You must access them through an object reference (obj.field)—or implicitly viathis.fieldinside an instance method or constructor of the same class. staticfields (class variables) belong to the declaring class, with one variable shared by instances of that class. The idiomatic syntax isClassName.staticField, though Java also permits accessing astaticfield through a reference expression (obj.staticField).
public class Ticket {
static int nextNumber = 100;
int serial;
public static void main(String[] args) {
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
t1.serial = 1;
t2.serial = 2;
t1.nextNumber = 500; // Legal, though Ticket.nextNumber = 500 is preferred
System.out.println(t1.serial + " " + t2.serial + " " + t2.nextNumber);
}
}
This program prints 1 2 500. Changing t1.nextNumber modifies the single shared Ticket.nextNumber variable, so t2.nextNumber observes 500, whereas t1.serial and t2.serial remain independent.
The Classic null Reference Gotcha: Instance vs. static Access
Dereferencing a null variable to read or write an instance field throws a NullPointerException at runtime because there is no heap object to inspect. By contrast, accessing a static field (or calling a static method) through a null reference variable compiles and executes without throwing NullPointerException!
Why? The Java compiler resolves static members at compile time using the declared type of the reference expression, never the runtime object behind it. The qualifier expression is evaluated, and its value is discarded. For example, lookup().nextNumber calls lookup() first. If that call throws, static access does not complete. If the call returns null, the static field can still be read.
public class NullStaticTrap {
static String tag = "SE8";
int count = 7;
public static void main(String[] args) {
NullStaticTrap ghost = null;
System.out.println(ghost.tag); // Prints: SE8 (NO NPE!)
System.out.println(((NullStaticTrap) null).tag); // Prints: SE8 (cast gives type)
// System.out.println(null.tag); // COMPILE ERROR: <null> cannot be dereferenced
System.out.println(ghost.count); // Compiles, throws NullPointerException at runtime
}
}
Warning
Notice the distinction between ghost.tag and null.tag: a typed variable holding null (ghost) or an explicit cast (((NullStaticTrap) null).tag) provides a class type at compile time, so static lookup succeeds. Writing null.tag directly fails to compile because literal null has no class type.
Object Creation & Initialization Order
The Java SE 8 Associate exam regularly tests the exact execution sequence when creating an instance of a subclass. Initialization has two stages. Class initialization occurs on the first active use that requires it. Instance initialization occurs as part of constructing each new instance. The table follows an ordinary superclass/subclass trace with neither class already initialized, no static constant variables, and initializers that complete normally.
| Step | Phase | What Executes | Frequency |
|---|---|---|---|
| 1 | Class Init | Superclass static fields & static { } blocks (textual order) | Once per class |
| 2 | Class Init | Subclass static fields & static { } blocks (textual order) | Once per class |
| 3 | Instance Init | new allocates heap memory and zeroes all instance fields (0, false, null) | Every new |
| 4 | Instance Init | The superclass constructor chain reaches Object. On the way back, the superclass’s field initializers and instance blocks run in source order. | Every new |
| 5 | Instance Init | Superclass constructor body executes | Every new |
| 6 | Instance Init | Subclass instance fields & { } blocks (textual order) | Every new |
| 7 | Instance Init | Subclass constructor body executes | Every new |
Trace the following complete example carefully—including a subtle twist about where main lives:
class Base {
static int sb = log("1. Base static field");
static { log("2. Base static block"); }
int ib = log("5. Base instance field");
{ log("6. Base instance block"); }
Base() { log("7. Base constructor"); }
static int log(String msg) {
System.out.println(msg);
return 1;
}
}
public class Derived extends Base {
static int sd = log("3. Derived static field");
static { log("4. Derived static block"); }
int id = log("8. Derived instance field");
{ log("9. Derived instance block"); }
Derived() { log("10. Derived constructor"); }
public static void main(String[] args) {
System.out.println("--- main starts ---");
new Derived();
System.out.println("--- second new ---");
new Derived();
}
}
Look closely at the exact console output when running java Derived:
1. Base static field
2. Base static block
3. Derived static field
4. Derived static block
--- main starts ---
5. Base instance field
6. Base instance block
7. Base constructor
8. Derived instance field
9. Derived instance block
10. Derived constructor
--- second new ---
5. Base instance field
6. Base instance block
7. Base constructor
8. Derived instance field
9. Derived instance block
10. Derived constructor
Two key exam insights emerge from this trace:
- Why lines 1–4 print before
--- main starts ---: InvokingDerived.mainis an active use ofDerived, so the JVM initializesBaseandDerivedstaticmembers before enteringmain. Ifmainwere placed in an unrelatedRunnerclass that printed--- main starts ---first, lines 1–4 would wait untilnew Derived()executed. - Why
second newskips lines 1–4: Static fields andstaticinitializer blocks execute only once when the class is initialized, whereas instance fields, instance initializer blocks, and constructors execute on everynew Derived()call.
The Forward-Reference Rule in Field Initializers
Because Java executes field initializers and initializer blocks in top-to-bottom textual order, the compiler enforces JLS §8.3.3 to prevent reading an uninitialized field by simple name before its declaration:
Important
Inside a field initializer or initializer block, you cannot read a field declared textually later in the same class by its simple name (illegal forward reference). The exact same rule applies to static fields inside static initializers.
The compile-time check concerns a read by simple name in an initializer of the same kind, such as an instance initializer reading a later instance field. Compare these patterns:
| Pattern | Compiles? | Behavior |
|---|---|---|
Reading later field by simple name (int a = b; int b = 5;) | No | Compile error: illegal forward reference |
Assigning to a later field ({ b = 10; } int b = 5;) | Yes | Assignment target is legal; later initializer b = 5 overwrites 10 |
Qualifying with this. or ClassName. (int a = this.b; int b = 5;) | Yes | Bypasses simple-name check; reads the field's default zero value (0) |
| Reading later field inside a method or constructor body | Yes | Method/constructor bodies are exempt from textual declaration-order restriction |
public class ForwardRefCheck {
// int bad = target; // COMPILE ERROR: illegal forward reference
int viaThis = this.target; // VALID: reads default value 0 before target = 5 runs
{ target = 20; } // VALID: simple assignment target allowed
int target = 5; // runs next in textual order, overwriting 20 with 5
int viaMethod = getTarget(); // VALID: method reads target after target’s initializer has completed
int getTarget() { return target; }
public static void main(String[] args) {
ForwardRefCheck f = new ForwardRefCheck();
System.out.println(f.viaThis + " " + f.target + " " + f.viaMethod);
}
}
Tracing ForwardRefCheck step by step: heap allocation sets viaThis = 0, target = 0, viaMethod = 0; then viaThis = this.target reads 0; { target = 20; } sets target to 20; int target = 5; overwrites target with 5; finally getTarget() returns 5. The output is 0 5 5.
What happens when the following class is compiled and executed?
public class Probe {
static String mode = "AUTO";
String label = "Main";
public static void main(String[] args) {
Probe p = null;
System.out.print(p.mode + ":");
System.out.print(p.label);
}
}
Compilation fails because p is null when accessing p.mode
Throws NullPointerException before printing anything
Prints AUTO: and then throws NullPointerException
Prints AUTO:Main without throwing an exception
Given the class hierarchy below, in what order are the messages printed when new Child() is called from an external Launcher.main method, assuming neither class has been initialized before the call?
class Parent {
static { System.out.print("PS "); }
{ System.out.print("PI "); }
Parent() { System.out.print("PC "); }
}
class Child extends Parent {
static { System.out.print("CS "); }
{ System.out.print("CI "); }
Child() { System.out.print("CC "); }
}
PS CS PI PC CI CC
PS PI PC CS CI CC
CS PS CI CC PI PC
PS CS PI CI PC CC
Which class compiles cleanly under Java SE 8 without a forward-reference error?
class A { int x = y + 1; int y = 10; }
class B { static int x = y; static int y = 4; }
class C { int x = this.y; { y = 9; } int y = 3; }
class D { { int z = y; } int y = 5; }
Sections you finish are checked off in the contents.