Java Reference
In-Depth Information
public InstanceInitializer() {
System.out.println("Inside no-args constructor.");
}
public static void main(String[] args) {
InstanceInitializer ii = new InstanceInitializer();
}
}
Inside instance initializer 1.
Inside instance initializer 2.
Inside no-args constructor.
an instance initializer cannot have a return statement. It cannot throw checked exceptions unless all declared
constructors list those checked exceptions in their throws clause; an exception to this rule is made in the case of an
anonymous class because it does not have a constructor; an instance initializer of an anonymous class may throw
checked exceptions.
Tip
static Initialization Block
A static initialization block is also known as a static initializer. It is similar to an instance initialization block. It is
used to initialize a class. In other words, you can initialize class variables inside a static initializer block. An instance
initializer is executed once per object whereas a static initializer is executed only once for a class when the class
definition is loaded into JVM. To differentiate it from an instance initializer, you need to use the static keyword in
the beginning of its declaration. You can have multiple static initializers in a class. All static initializers are executed
in textual order in which they appear, and execute before any instance initializers. Listing 6-33 demonstrates when a
static initializer is executed.
Listing 6-33. An Example of Using a static Initializer in a Class
// StaticInitializer.java
package com.jdojo.cls;
public class StaticInitializer {
private static int num;
// An instance initializer
{
System.out.println("Inside instance initializer.");
}
// A static initializer. Note the use of the keyword static below.
static {
num = 1245;
System.out.println("Inside static initializer.");
}
 
 
Search WWH ::




Custom Search