Java Reference
In-Depth Information
Instance Initializers
An instance initializer is similar to a static initializer, except that an instance
initializer executes each time an object of the class is instantiated. The differ-
ence between an instance initializer and a constructor is that an instance ini-
tializer executes before the constructor is invoked.
An instance initializer is simply a block of code within curly braces that
appears in a class. For example, the CDPlayer class in the following contains
an instance initializer. Notice that no keyword is used and no name is given to
the instance initializer.
public class Electronics
{
public Electronics()
{
System.out.println(“Constructing an Electronics”);
}
}
public class CDPlayer extends Electronics
{
private int songNumber;
public CDPlayer(int x)
{
super();
System.out.println(“Constructing a CDPlayer”);
songNumber = x;
}
{
System.out.println(“Inside instance initializer”);
}
}
The instance initializer in the CDPlayer is the following block of code:
{
System.out.println(“Inside instance initializer”);
}
The statements in an instance initializer execute after any parent class con-
structors are invoked, but before the child class constructor executes. When an
object is instantiated and the class contains an instance initializer, the follow-
ing events occur in the order shown:
Search WWH ::




Custom Search