If your default implementation is rather trivial and likely to stay that way, and if nothing extends it or is likely to, this is probably the way to go. You don't want to put it in its own file, and where else would you put it? I'd suggest making the class private with a public instance (assuming no state):
/** An interface a lot like java.util.Collection. */
public interface WhatEver {
private class Default implements Whatever {
// Methods...
}
/** A default implementation that is always empty. Suitable as a NULL value. */
public final WhatEver DEFAULT = new Default();
// Rest of interface...
I don't think it would make any difference to execution (there's no data in the class instances), but you'd get better Javadoc. And you could use an anonymous class and save a line of code.
You might even want a few other "default" instances. For a collection-like interface, you might have one with a single, default entry, or an infinite number (hasNext
always returns true
) of the same default entry.
I think the key is the default implementations cannot depend on anything outside of the interface. Use no outside classes and interfaces unless they were referenced in the main body of the interface proper, and no outside classes extending the defaults. The interface becomes a bit more than the standard idea of an interface, but still stands on its own.
Another key point would be that you don't want too much code in one .java file, but you don't want too little, either.