Skip to content

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
}
  1. Parent class first. Movie extends Content, so Content is set up before Movie.
  2. Static fields, in the order they appear: views gets 0.
  3. Static blocks, in the order they appear. A static block is static followed by braces. Here it adds 10, so views ends at 10.

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:

ABC
  • main lives in StreamingApp, so Java must set up this class before main starts. That is why A and B come before C.
  • The two new StreamingApp() calls print nothing: the class is already set up.
  • The static blocks run in file order. The B block sits below main, but it still runs before main: what counts is its position in the file, not its position relative to main.

Once the class is ready, Java can start building the object itself.

๐Ÿ’ป Code: Java17_Part_6_Object_Oriented_Basics on GitHub

Next: building an object โ†’