class
Initialization order example
With this example we are going to demonstrate what happens when there are changes in the initialization order of classes. The steps of the example are described in short:
- We have created class
A
, with a constructor that gets an int val and prints it. - We have also created class
Cr
. - In the
Cr
we use theA
constructor to create three newA
objectsa
,a2
anda3
. In theCr
constructor we reinitializea3
object.Cr
also has a methodfunction()
. - We create a new instance of
Cr
calling its constructor. All threea
,a2
,a3
objects are initialized and thena3
is reinitialized in theCr
constructor.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; class A { A(int val) { System.out.println("A(" + val + ")"); } } class Cr { A a = new A(1); // Before constructor Cr() { // Indicate we're in the constructor: System.out.println("Cr()"); a3 = new A(33); // Reinitialize t3 } A a2 = new A(2); // After constructor void function() { System.out.println("function()"); } A a3 = new A(3); // At end } public class InitializationOrder { public static void main(String[] args) { Cr t = new Cr(); t.function(); // Shows that construction is done } }
Output:
A(1)
A(2)
A(3)
Cr()
A(33)
function()
This was an example of what happens when there are changes in the initialization order of classes in Java.