Instance Initializer In Java

In my previous example I have explained how to use static initializer in Java.This example shows how to use the instance initializer block in Java. The following are the few features of instance blocks.

  • Instance initializers are block of code with out any keyword keyword. The code which needs to be initialized will be put inside the braces {}. These are executed when the instance is created for the first time by any application.
  • Static and instance variables can be initialized inside instance blocks.
  • Any number of instance blocks can be defined, that will be executed in the order of definition. Instance initializer blocks will be executed after the static initializer blocks.
  • Instance and static methods can be called from the instance initializers.
  • Instance blocks are used for initializing the instance variables at the time of creating the instance of that class.

Lets look at the simple example snippet shows how to use the instance initializer.

JavaInstanceInitializerExample.java

package javabeat.net.core;

/**
 * Java Instance Initializer Example
 *
 * @author Krishna
 *
 */
public class JavaInstanceInitializerExample {

	//Static variable
	static int j = 0;

	//Instance variable
	int i = 0;

	{
		System.out.println("Instance Initializer Called");
		i = 0; // instance variable can be initialized
		j = 10; //Initialize static variable
		instanceMethod();
	}
	static{
		System.out.println("Static Initializer Called");
		testMethod();//Can invoke static method, not instance methods
	}

	//Static method
	public static void testMethod(){
		System.out.println("Static 'testMethod()' called");
	}
	//Static method
	public static void instanceMethod(){
		System.out.println("Instance 'instanceMethod()' called");
	}

	public static void main(String[] args) {
		System.out.println("J Value Before Instance Initializer Called : "+j);
		new JavaInstanceInitializerExample();
		System.out.println("J Value After Instance Initializer Called : "+j);
	}
}

Output…

If you look at the above code, the order of executing the blocks are clear. Also note that variable “j” is not initialized untill the instance initializer is invoked.

Static Initializer Called
Static 'testMethod()' called
J Value Before Instance Initializer Called : 0
Instance Initializer Called
Instance 'instanceMethod()' called
J Value After Instance Initializer Called : 10

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*