Since all of the code examples here use anonymous classes, I threw together this (slightly horrifying) class that demonstrates using instance initializers in a "proper" class. You can use them to do complex processing or handle exceptions at initialization time. Notice that these blocks are run before the constructor is run, but the constructor is run before initializers in a child class are run:
import java.util.Scanner;
public class InstanceInitializer {
int x;
{
try {
System.out.print("Enter a number: ");
x = Integer.parseInt(new Scanner(System.in).nextLine());
} catch (NumberFormatException e) {
x = 0;
}
}
String y;
{
System.out.print("Enter a string: ");
y = new Scanner(System.in).nextLine();
for(int i = 0; i < 3; i++)
y += y;
}
public InstanceInitializer() {
System.out.println("The value of x is "+x);
System.out.println("The value of y is "+y);
}
public static class ChildInstanceInitializer extends InstanceInitializer {
{
y = "a new value set by the child AFTER construction";
}
}
public static void main(String[] args){
new InstanceInitializer();
new InstanceInitializer();
System.out.println();
System.out.println(new ChildInstanceInitializer().y);
// This is essentially the same as:
System.out.println(new InstanceInitializer(){
{y = "a new value set by the child AFTER construction";}
}.y);
}
}
This outputs (something like):
Enter a number: 1
Enter a string: a
The value of x is 1
The value of y is aaaaaaaa
Enter a number: q
Enter a string: r
The value of x is 0
The value of y is rrrrrrrr
Enter a number: 3
Enter a string: b
The value of x is 3
The value of y is bbbbbbbb
a new value set by the child AFTER construction
Enter a number: s
Enter a string: Hello
The value of x is 0
The value of y is HelloHelloHelloHelloHelloHelloHelloHello
a new value set by the child AFTER construction
Notice that the "new value" string is not set until after the parent class's constructor has already been called.