Skip to content

Building an object, step by step

โ˜• Java 17 ยท The Order Java Builds Your Objects In ยท 2/4

The class is set up. Now new builds the object, and this part runs again for every object you create.

From new to a ready object

class Movie extends Content {
    static int plays = 0;            // static field
    private String quality = "HD";   // instance field
    { plays++; }                     // instance block
    private final String title;

    Movie(String t) { title = t; }   // constructor body
}

When you write new Movie("Dune"):

  1. Class set up? If Movie isn't set up yet, Java does the class setup first (page 1).
  2. Parent part first. The first line of every constructor is this(...) or super(...). If you write neither, the compiler adds super();.
  3. Instance fields and blocks, top to bottom. An instance block is a pair of braces with no keyword.
  4. Constructor body. When constructors call each other with this(...), the last one called finishes first.

Tracing one class

public class Player {
    private String quality = "HD";
    { System.out.print(quality + "-"); }

    private static int viewers = 0;
    static { System.out.print(viewers + "-"); }
    static { viewers += 5; System.out.print(viewers + "-"); }

    public Player() { System.out.print("play-"); }

    public static void main(String... args) { new Player(); }
}

Output:

0-5-HD-play-
Step Code Prints
Class setup viewers = 0, then both static blocks in file order 0- 5-
Object setup quality = "HD", then the instance block HD-
Constructor Player() body play-

The static code is written below the instance code, yet it runs first: class setup always comes before object setup.

So far there was no parent class to worry about. Next: what happens when classes inherit from each other.

๐Ÿ’ป Code: Java17_Part_6_Object_Oriented_Basics on GitHub

โ† Class setup ยท Next: parents and final fields โ†’