Originally posted by Corey McGlone:
Think about what it means to be a static initializer or instance initializer.
What I do not fully understand is why it didn't print 4 initially. One explanation I gave myself is that it has not execute that part yet. I tried to put static int classMember2 = 4; right after static int classMember1 = 3, it will be 4.
Isn't a static variable initialized during class load?
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
* T is a class and an instance of T is created.
* T is a class and a static method declared by T is invoked.
* A static field declared by T is assigned.
* A static field declared by T is used and the reference to the field is not a compile-time constant (�15.28) . References to compile-time constants must be resolved at compile time to a copy of the compile-time constant value, so uses of such a field never cause initialization.
Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization. A class or interface will not be initialized under any other circumstance.
The intent here is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (�184.108.40.206). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
Originally posted by Jose Botella:
That was exactly the intention of Corey when placing fields both before and after the sentences that print them: It is showing that initializers are executed in textual order. But, before the fields are intialized they had been assign their defaults values. You know, 0 for all integer types, 0.0 for floating point types, null for objects and "\u0000" for char. That is why they print their default value when they are accessed before they have been initialized.
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koophttps://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton