Hi Terry,
Instance initialization block (non-static block !!) is useful for the anonymous inner class because it cannot "define" a constructor.
Following code (though not very useful) shows itz use.
class A{
public static void main(
String args[]) {
A a = new A();
B b = a.tester(10);
b.bTester();
B b2 = a.tester2(20);
b2.bTester();
}
public B tester(final int x) {
return new B() {
// Instance variable for the anonymous class.
int i;
int y;
// Use the instance initialization like a constructor
{
i = x;
y = i + x;
}
public void bTester() {
i = i++; // ???
System.out.println("I ---> " + i);
System.out.println("Y ---> " + y);
}
};
}
// 2nd version, this method creates and returns an anonymous inner class which
// extends the abstract class B. The anonymous class calls the 2nd constructor
// of its super class "B", B(int i).
public B tester2(final int x) {
// This anonymous class is not defining a constructor. Its just calling
// the super class constructor
return new B(x) {
// Instance variables for the anonymous class.
int i;
int y;
// Use the instance initialization like a constructor
{
i = x;
y = i + x;
}
public void bTester() {
i = i++; // ???
System.out.println("I (v2) ---> " + i);
System.out.println("Y (v2) ---> " + y);
}
};
}
}
abstract class B {
public B() {
}
public B(int i) {
}
public abstract void bTester();
}
Originally posted by Terry McKee:
Thanks for all of the reponses. I can understand why you would use static blocks, but wouldn't it be good programming to use the actual constructors for coding rather than non-static blocks?