According to Java specs, more correctly it should be called NestedClassInInterface
For example:
public interface XXXVisitor { public final static XXXVisitor NULL = new Null();void visit(R r); void visit(T t);
/* Null implementation of XXXVisitor does nothing */ public static class Null implements XXXVisitor { public void visit(R r) {}; public void visit(T t) {}; } }
Same thing can also be accompilsed using AnonymousInnerClasses.
public interface Node {
public Node getNext(); //next node in this list public final static Node NULL = new Node() { public Node getNext(){ return Node.NULL /* you dont have any next object but just your self */ } }}
The problem with AnonymousInnerClasses happens when implementation class needs to be serializable as well as overide equals(). You have to incorporate a state into this object.
No we won't because all the methods of the interface are nullified ( nill implementation).
A slightly different slant:
public interface XmlOutput? { public static final Util UTIL = new Util( );Classes that implement this interface have direct access to UTIL - thuspublic Element toXml( );
public static class Util { public Element forCollection( String parentName , Collection items ) { return forCollection( new Element( parentMane ) , items ); }
public Element forCollection( Element parent , Collection items ) { for( Iterator i = items.iterator( ) ; items.hasNext( ) ; ) { XmlOutput? item = ( XmlOutput? ) item.next( ); parent.addChild( item.toXml( ) ); } return parent } } }
public Element toXml( ) { return UTIL.forCollection( "Foo" , getFoos( ) ); }I also like to place adapter implementations in interfaces where appropriate.
I find inner classes inside interfaces confusing. The primary goal of interface is to declare contract between implementation class and its user. It is ok to put constants there even in the form of inner classes but placing your logic to be just inappropriate. If you need namespace use subpackages .... --KirillStepanosov
This page mirrored in JavaIdioms as of April 29, 2006