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:
Post a Comment