Brian's Waste of Time

Wed, 21 Jan 2004

Constructors in Anonymous Inner Classes

A coworker did something that got a good double take today... he put a "constructor" in an anonymous inner class. Java has a nice feature where you can plop down a block anywhere in the class and it gets appended to the constructor, so:


public class Silly {
    public Silly() {
        System.out.println("1");
    }
    
    public void neverCalled() {
        System.out.println("Wheeeeeeee!");
    }
    
    {
        System.out.println("2");
    }
}

When instantiated will print 1 and 2. You can additionally set a static block which is executed when the class is initially loaded, but I don't want to think how that will work with anonymous inner classes right now. Anyway, he did this to make sure his anonymous inner class was initialized properly.

It's only January and I think the scary-ass-code-of-the-year award has already been won =)

11 writebacks [/src/java] permanent link