July 09, 2005

Heavy Java interfaces

There's one thing I never realized about Java until recently: You are allowed to go crazy with nesting. Say you have a simple interface:

public interface Interface {
    public void foo();
}

You could now nest an implementation of that inside the interface and make that implementation available in a singleton-ish fashion, all in the same file:

public interface Interface {

    public void foo();

    public class InterfaceImpl implements Interface {
        public void foo() { }
    }

    public static Interface INSTANCE = new InterfaceImpl();

}

You may now write Interface i = Interface.INSTANCE. Let's make this look even more wrong and implement Interface on the fly:

public interface Interface {

    public void foo();

    public static Interface INSTANCE = new Interface() {
        public void foo() { }
    };
	
}

By now you should feel an urgent need to wash your hands.

Comments

Post a comment

Thanks for signing in, . Now you can comment. (sign out)

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)


Remember me?