views:

127

answers:

2
+2  Q: 

Inner Interfaces?

I'm pretty new to Java and I don't understand what is this structure. I know what is an interface and how is defined, but in this case, I really don't know. Could you tell what is about?

public interface WebConstants {
    public interface Framework {
        String ACTION = "action";
    }

    public interface Look {
        String LIST_CONT = "list.cont";
    }
}
+1  A: 

Every field inside an interface is implicitly public, static, and final. In this case WebConstants declares an inner interface (public, static, and final) Framework and (public, static, and final) Look which have also some (public, static, and final) String fields.

This is a (not very common) way to order constants in your code, with this structure you could type:

String action = WebConstants.Framework.ACTION;

String list = WebConstants.Look.LIST_CONT;

The advantage of this is that since the WebConstants is an interface you can't accidentally instanciate it

victor hugo
You can't prohibit client classes from "implementing" a constant interface, which is very bad practice as it makes a compile-time utility (accessing the constants without prefixing them) part of the client's external interface. Classes, on the other hand, can be made uninstantiable (with private constructors that unconditionally `throw new AssertionError()` or something like it), and are therefore better alternatives to put constants in than interfaces. With `import static` there's no reason at all to use constant interfaces.
gustafc
@gustafc I totally agree
victor hugo
A: 

You might want to look into enums if you're looking at using a similar solution:

public enum WebConstants
{
    ACTION("action"), LIST_COUNT("list.count");

    private String display;

    private WebConstants(String display)
    {
        this.display = display;
    }

    public String getDisplay()
    {
        return display;
    }
}

So you could use it calling WebConstants.ACTION.getDisplay().

Having an interface of constants doesn't really make any sense to me. A better way of doing things might be to have abstract accessor methods.

public interface ActionAware
{
    public String getAction();
}

public interface ListCountAware
{
    public String getListCount();
}

public abstract class AbstractUseCase implements ActionAware, ListCountAware
{

    public void doSomething()
    {
        String action = getAction();
        String listCount = getListCount();
    }

}

public final class SpecificUseCase extends AbstractUseCase
{
     public final static String ACTION = "specific.action";
     public final static String LIST_COUNT = "specific.list.count";

     public String getListCount()
     {
         return LIST_COUNT;
     }

     public String getAction()
     {
         return ACTION;
     }

     // other methods

}
Droo