Initialization Order in Java

I want to ask why java initializes static objects before non-stationary objects?
in this example, b3 will be initialized after b4 and b5:

class Cupboard { 
    Bowl b3 = new Bowl(3); 
    static Bowl b4 = new Bowl(4); 
    Cupboard() {}
    static Bowl b5 = new Bowl(5); 
}
+5
source share
5 answers

Because static class members are created and initialized (during class loading) before any class instance is ever created, they can be accessed without creating an instance of the class. Non-static members are created for each instance and thus wait for the instance to be created for initialization for that instance.

+17
source

. , Java . .

+3
  • static .

  • () , .

+2

.

. , , , , . , , :

class Foo
{
    private static final Foo FOO_BAR = new Foo("bar");
    private static final Foo FOO_BAZ = new Foo("baz");

    private final String name;

    public Foo(String n)
    {
        name = n;
    }

    [...]
}

Here, the name in the first instance is initialized to "bar" before initializing FOO_BAZ.

+2
source

Imagine that static variables are class variables, not objects of this class. This is one level higher. If Java supports metaclasses, classes will be created from metaclasses when they are declared, and their static members can be accessed even if instances of these classes do not exist. So you really need to have static elements before non-static.

+1
source

All Articles