InitBlockDemo.java
Download InitBlockDemo.java
1: /* Demo of initialization blocks in Java.
2: *
3: * Written 8/2005 by Wayne Pollock, Tampa Florida USA
4: * Updated 2/2021: expanded the details on the steps.
5: *
6:
7: These are the 12 steps to initialize an object f from the code Foo f=new Foo();
8: 1. The Classloader locates Foo.class file on disk, and any dependent classes
9: (e.g., superclasses).
10: 2. Byte code is verified.
11: 3. Class objects for dependent classes are found on disk, created, and
12: initialized (each using these same steps 1-6).
13: 4. Sufficient memory is allocated for all Class object's fields, including all
14: static fields in the class Foo.
15: 5. All static fields are initialized to default (zero, false, null) values.
16: 6. Static fields and static initialization blocks are executed in the order
17: they appear.
18:
19: The remaining steps are per-object:
20:
21: 7. Sufficient memory is allocated for all instance fields, included inherited
22: ones.
23: 8. All instance properties are initialized to default (zero, false, null) values.
24: 9. The parent class' instance fields are initialized (including any
25: initialization blocks).
26: 10. The parent class' constructor is run to finish initializing inherited fields.
27: 11. Instance variable initialization expressions and initialization blocks are
28: executed in the order they appear.
29: 12. The body of the matched constructor is executed.
30:
31: Steps 1–6 occur only once in the lifetime of the JVM. The rest occur each time
32: a new object is created.
33: */
34:
35: class InitBlockDemo {
36: private static int nextID;
37: public int idNum;
38: public String name;
39:
40: static {
41: nextID = 1; // complex DB lookup goes here
42: // Add shutdown hook here
43: }
44:
45: {
46: idNum = nextID++; // Run before any constructor
47: }
48:
49: InitBlockDemo () {
50: this( "unknown" ); // Constructor chaining
51: }
52:
53: InitBlockDemo ( String name ) {
54: // Object's no-arg constructor is invoked here.
55: this.name = name;
56: }
57:
58: public static void main ( String [] args ) {
59: InitBlockDemo ibd1 = new InitBlockDemo( "Hymie" );
60: InitBlockDemo ibd2 = new InitBlockDemo();
61: System.out.println( "ibd2.idNum = " + ibd2.idNum );
62: }
63: }