Class setup: static code runs first¶
โ Java 17 ยท The Order Java Builds Your Objects In ยท 1/4
Two moments, then the constructor¶
Every object goes through two setup moments before its constructor finishes:
| Moment | What runs | How often |
|---|---|---|
| 1. Class setup | parent class first, then static fields and static blocks | once per class |
| 2. Object setup | parent part first, then instance fields and instance blocks | on every new |
| 3. Constructor | bodies run from the parent down to the child | on every new |
Three rules cover almost everything:
- Static code belongs to the class and runs once.
- Instance code belongs to each object and runs on every
new. - Inside a class, Java runs fields and blocks from top to bottom.
The three steps of class setup¶
class Content { }
class Movie extends Content {
static int views = 0; // 2. static fields, top to bottom
static { views += 10; } // 3. static blocks, top to bottom
}
- Parent class first.
MovieextendsContent, soContentis set up beforeMovie. - Static fields, in the order they appear:
viewsgets0. - Static blocks, in the order they appear. A static block is
staticfollowed by braces. Here it adds 10, soviewsends at10.
A class is set up at most once, just before its first use. Create one object or a thousand: its static code runs a single time.
When exactly is a class set up?¶
public class StreamingApp {
static { System.out.print("A"); }
public static void main(String[] args) {
System.out.print("C");
new StreamingApp();
new StreamingApp();
}
static { System.out.print("B"); }
}
Output:
mainlives inStreamingApp, so Java must set up this class beforemainstarts. That is whyAandBcome beforeC.- The two
new StreamingApp()calls print nothing: the class is already set up. - The static blocks run in file order. The
Bblock sits belowmain, but it still runs beforemain: what counts is its position in the file, not its position relative tomain.
Once the class is ready, Java can start building the object itself.