开发者

order of initialization in Java

开发者 https://www.devze.com 2022-12-27 16:45 出处:网络
I want to ask why java initializes the static objects before the non-static objects ? in this example b3 w开发者_如何学JAVAill be initialized after b4 and b5 :

I want to ask why java initializes the static objects before the non-static objects ?

in this example b3 w开发者_如何学JAVAill 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); 
}


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


Because the class is initialized before the instance is. When the class is loaded, Java runs any static blocks and initializes static variables. However, non-static instance variables aren't created nor initialized until an instance is created.


  • static variables are initialized at the time the class is loaded.

  • instance variables (non-static) are initialized after an object of this class is constructed, which is after the class was loaded.


Static variables are initialized when the class is loaded.

Instance variables are initialized when the instance is constructed. Most of the time this is after the class is fully initialized, but contrary to what the others have written this may also happen while initializing static variables. For example, it is quite common to have static constants for commonly used instances of a class, like this:

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 name in the first instance is initialized to "bar" before FOO_BAZ is initialized.


Just imagine static variables are variables of the class, not the objects of that class. This is sort of one level above instances. If Java supported metaclasses, classes would be instantiated from metaclasses when they are declared and their static members could be accessed even if no instances of those classes exist. So you really need to have static members before non-static.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号