Initialization of Java static data

Posted by ciaranmg on Wed, 27 Nov 2019 19:07:10 +0100

No matter how many objects are created in Java, static data only occupies one storage area.

The following program example initializes a static storage area:

//: initialization/StaticInitialization.java
// Specifying initial values in a class definition.

class Bowl{
    // constructor
    Bowl(int marker){
        System.out.println("Bowl("+marker+")");
    }
    // Method
    void f1(int marker){
        System.out.println("f1("+marker+")");
    }
}

class Table{
    // Static domain
    static Bowl bowl1 = new Bowl(1);
    // constructor
    Table(){
        System.out.println("Table()");
        bowl2.f1(1);
    }
    // Method
    void f2(int marker){
        System.out.println("f2("+marker+")");
    }
    // Static domain
    static Bowl bowl2 = new Bowl(2);
}

class Cupboard{
    // Non static domain
    Bowl bowl3 = new Bowl(3);
    // Static domain
    static Bowl bowl4 = new Bowl(4);
    // constructor
    Cupboard(){
        System.out.println("Cupboard()");
        bowl4.f1(2);
    }
    // Method
    void f3(int marker){
        System.out.println("f3("+marker+")");
    }
    // constructor
    static Bowl bowl5 = new Bowl(5);
}
public class StaticInitialization{
    public static void main(String[] args){
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        System.out.println("Creating new Cupboard() in main");
        new Cupboard();
        table.f2(1);
        cupboard.f3(1);
    }
    static Table table = new Table();
    static Cupboard cupboard = new Cupboard();
}
---------- Java ----------
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)

Output completed (0 sec consumed) - Normal Termination

The order of initialization is: static objects first, then "non static" objects.

To execute main(), the StaticInitialization class must be loaded, and then its static fields table and cupboard are initialized, which causes their corresponding classes to be loaded, and because they both contain static Bowl objects, the Bowl is also loaded later. In this way, all classes in this particular program are loaded before main () starts.

Personal understanding: first, load the staticinitialization class from the main() function, then initialize the static domain Table in the staticinitialization class, load the Table class, which contains the static Bowl object, then load the Bowl class, load the Bowl class builder to create the bowl1 object, output the Bowl(1), load the Bowl class builder to create the bowl2 object, and output the Bowl(2); the same as To create a cupboard object.

It should be noted that bowl3 is a non static domain, and a Bowl object will be created every time the Cupboard object is created.

Topics: Java