Today, I will briefly mention about the class initialization. When we execute any java program (e.g.: java InitTest), Java Virtual Machine loads and link the class, execute initializers, and invokes the main class. Initialization process has some rules. Before we go into the details, spend a few minutes to figure out the output.
class SuperClass { static { System.out.print("0 "); } } public class InitTest extends SuperClass{ public InitTest(){ s1 = sM1("1"); } static String s1 = sM1("a"); String s3 = sM1("2");{ s1 = sM1("3"); } static{ s1 = sM1("b"); } static String s2 = sM1("c"); String s4 = sM1("4"); public static void main(String args[]){ InitTest it = new InitTest(); } private static String sM1(String s){ System.out.println(s); return s; } }
The order of initialization process are as follows:
- Superclasses are initialized before subclasses
- Static variable declarations and initializers are initialized in textual order
- Instance variable declarations and initializers are initialized in textual order
- Constructors
After InitTest is loaded, it must be initialized before main
can be invoked. Whether you created an instance of the class or not, first rule 1 and rule 2 runs. If the class is referred to without a new call, only rules 1 and 2 apply. Rule 3 and rule 4 relate to instances and constructors. They have to wait until there is code to instantiate the object.
Let’s execute the code step by step:
Rule 1: Superclasses are initialized before subclasses. SuperClass is initialized first.
static { System.out.print("0 "); } output: 0
Rule 2: Static variable declarations and initializers are initialized in textual order. Notice that the order of appearance in the class is important.
static String s1 = sM1("a"); static{ s1 = sM1("b"); } static String s2 = sM1("c"); Output: 0 a b c
Rule 3: Instance variable declarations and initializers are initialized in textual order. Again, the order is important.
String s3 = sM1("2"); { s1 = sM1("3"); } String s4 = sM1("4"); Output: 0 a b c 2 3 4
Rule 4: Constructors. After main method is invoked, a new class instance is explicitly created with new InitTest().
public InitTest(){ s1 = sM1("1"); } Output: 0 a b c 2 3 4 1
Thanks for reading!
For more information, see Java Language Specification.