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);
}
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.
Order of constructor execution... Parameterized constructor executed. Default constructor executed.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With