Inner Interfaces?

夙愿已清 提交于 2019-12-10 17:36:25

问题


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:


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




回答2:


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

}


来源:https://stackoverflow.com/questions/1482158/inner-interfaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!