Inner Class In Interface

Does anyone have ideas concerning putting InnerClassInInterface or any links to such things ? Thanks.

According to Java specs, more correctly it should be called NestedClassInInterface
You can make the NullObject for that interface an InnerClassInInterface -- JeroenMostert

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) {}; } }

Using AnonymousInnerClasses

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.

In the above example don't we have an infinite loop once you reach the Node.NULL at the end.Since when you ask the getNext it returns itself and getNext would again return it self so on and so forth

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( );

public 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? ) ); parent.addChild( item.toXml( ) ); } return parent } } }

Classes that implement this interface have direct access to UTIL - thus

    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

EditText of this page (last edited December 2, 2005)
FindPage by browsing or searching

This page mirrored in JavaIdioms as of April 29, 2006