Thursday, January 8, 2009

Anonymous class initializes parent's final field

Java allows to initialize the final fields in the constructor. The problem is that it fails to do so if the initialization is hidden inside construction of a subobject, likewise it is in the example below.

class C {
 final Object o; // never assigned
 {
  new Object() {
   {
   o = new Object(){}; // cannot assign
   }
  };
 }
 public static void main(String[] args) {
  System.out.println(new C());
 }
}

I think it is defect because anonymous class objects are ensured to run once and only once. Taking part in the parent construction they ensure one-time initialization of the parent's final field.

What makes it useful to unnecessarily block the useful code? I have noted that the most classes I instantiate throughout the GUI Swing hierarcy are unique: some special panel and special JList within another special panel. Instances of anonymous classes ideally fit the case. By contrast, it would be bad to bloat the code space with reusable (named) classes declarations with the only purpose to instantiate a single instance of it by the following extra line of code.

Occasionally, some of the deeply instantiated objects need to be referenced from the top. The described deficiency of Java unfortunately precludes us from using the final specifier for such references.

A note on double-brace initializers and named arguments proposal.
Parameter polymorphism: through method overriding or field initialization?

No comments: