The precedence of initializers and constructor to be called in a class

In a simple java class there are three approaches which will be initialized before any method does. So called static Initializer, Initializer and constructor. The predence of those methodologies is;

1. Static Initializer

2. Initializer: An initializer block is defined within a class, not as a part of a method. It executes for every object that’s created for a class.

3. Constructor: Constructors are special methods that create and return an object of the class in which they’re defined.

the below example will show you how it works out, I’ve literally changed the order so that you can simply apprehend the outcome

ConstructorExample Class

public class ConstructorExample {

	{
		System.out.println("I am invoked from the Initializer ");
	}

	static {
		System.out.println("I am invoked from the Static Initializer");
	}

	public ConstructorExample() {
		super();
		System.out.println("I am invoked from the User-defined Constructor");
	}

	public static void main(String[] args) {
		new ConstructorExample();
	}
}

Output

I am invoked from the Static Initializer
I am invoked from the Initializer 
I am invoked from the User-defined Constructor

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *