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 the A constructor to create three new A objects a, a2 and a3. In the Cr constructor we reinitialize a3 object. Cr also has a method function().
  • We create a new instance of Cr calling its constructor. All three a, a2, a3 objects are initialized and then a3 is reinitialized in the Cr 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:


  a3 = new A(33); // Reinitialize t3
    A a2 = new A(2); // After constructor

    void 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




This was an example of what happens when there are changes in the initialization order of classes in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button