Java Reference
In-Depth Information
Instance Initialization Block
You have seen that a constructor is used to initialize an instance of a class. An instance initialization block, also called
instance initializer, is also used to initialize objects of a class. Why does Java provide two constructs to perform the
same thing? Not all classes in Java can have a constructor. Are you surprised to learn that not all classes can have
constructors? I did not mention this fact during the discussion on constructors. Briefly, I mentioned inner classes,
which are different from top-level classes. I will discuss one more type of class in Chapter 2 of Beginning Java
Language Features (ISBN: 978-1-4302-6658-7) called an anonymous class. As the name suggests, an anonymous
class does not have a name. Recall that a constructor is a named block of code whose name is the same as the simple
name of the class. Because an anonymous class cannot have a name, it cannot have a constructor either. How will you
initialize an object of an anonymous class? You can use an instance initializer to initialize an object of an anonymous
class. The use of an instance initializer to initialize an object is not limited only to anonymous classes. Any type of
class can use it to initialize its object.
An instance initializer is simply a block of code inside the body of a class, but outside any methods or
constructors. Recall that a block of code is a sequence of legal Java statements enclosed within braces. An instance
initializer does not have a name. Its code is simply placed inside an opening brace and a closing brace. The following
snippet of code shows how to declare an instance initializer for the Test class. Note that an instance initializer is
executed in instance context and the keyword this is available inside the instance initializer.
public class Test {
private int num;
// An instance initializer
{
this.num = 101;
/* Other code for the instance initializer goes here */
}
/* Other code for Test class goes here */
}
You can have multiple instance initializers for a class. All of them are executed automatically in textual order
for every object you create. Code for all instance initializers are executed before any constructor. Listing 6-32
demonstrates the sequence in which the constructor and instance initializers are executed.
Listing 6-32. Example of Using an Instance Initializer
// InstanceInitializer.java
package com.jdojo.cls;
public class InstanceInitializer {
{
System.out.println("Inside instance initializer 1.");
}
{
System.out.println("Inside instance initializer 2.");
}
 
Search WWH ::




Custom Search