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
Crwe use theAconstructor to create three newAobjectsa,a2anda3. In theCrconstructor we reinitializea3object.Cralso has a methodfunction(). - We create a new instance of
Crcalling its constructor. All threea,a2,a3objects are initialized and thena3is reinitialized in theCrconstructor.
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.
