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"):
- Class set up? If
Movieisn't set up yet, Java does the class setup first (page 1). - Parent part first. The first line of every constructor is
this(...)orsuper(...). If you write neither, the compiler addssuper();. - Instance fields and blocks, top to bottom. An instance block is a pair of braces with no keyword.
- 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:
| 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.