Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order of initialization in Java

Tags:

java

I want to ask why java initializes the static objects before the non-static 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); 
}
like image 639
Mohamad Alhamoud Avatar asked Apr 16 '10 12:04

Mohamad Alhamoud


People also ask

What are the 3 ways of object initialization?

Assigning value to a variable is called initialization of state of an object. Initialization of variable means storing data into an object. 3. We can assign the value of variables in three ways: by using constructor, reference variable, and method.

What is the order of constructor execution in Java?

Order of constructor execution... Parameterized constructor executed. Default constructor executed.

How do you initialize a class variable in Java?

To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.

In what order is the constructor executed?

Constructors of nonvirtual base classes are executed, in the declaration order. Constructors of class members are executed in the declaration order (regardless of their order in the initialization list). The body of the constructor is executed.


1 Answers

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.

like image 117
Amber Avatar answered Sep 29 '22 02:09

Amber