接口内部的枚举实现 - Java

Joe*_*oey 31 java enums enumeration interface

我有一个关于在界面中放置Java枚举的问题.为了更清楚,请参阅以下代码:

public interface Thing{
   public enum Number{
       one(1), two(2), three(3);
       private int value;
       private Number(int value) {
            this.value = value;
       }
       public int getValue(){
        return value;
       }
   }

   public Number getNumber();
   public void method2();
   ...
}
Run Code Online (Sandbox Code Playgroud)

我知道接口包含空体的方法.但是,我在这里使用的枚举需要一个构造函数和一个方法来获取相关的值.在此示例中,建议的接口不仅包含具有空体的方法.是否允许此实施?

我不确定是否应该将enum类放在接口或实现此接口的类中.

如果我将枚举放在实现此接口的类中,那么public Number getNumber()方法需要返回枚举类型,这将迫使我在接口中导入枚举.

Jac*_*ack 27

在一个enum内部声明是完全合法的interface.在您的情况下,接口仅用作枚举的命名空间,仅此而已.无论您在何处使用,都可以正常使用该界面.

  • 当然没关系,`enum`中包含的任何东西都是它的一部分而不是`interface`. (2认同)

小智 6

以下列出了以上事项的示例:

public interface Currency {

  enum CurrencyType {
    RUPEE,
    DOLLAR,
    POUND
  }

  public void setCurrencyType(Currency.CurrencyType currencyVal);

}


public class Test {

  Currency.CurrencyType currencyTypeVal = null;

  private void doStuff() {
    setCurrencyType(Currency.CurrencyType.RUPEE);
    System.out.println("displaying: " + getCurrencyType().toString());
  }

  public Currency.CurrencyType getCurrencyType() {
    return currencyTypeVal;
  }

  public void setCurrencyType(Currency.CurrencyType currencyTypeValue) {
    currencyTypeVal = currencyTypeValue;
  }

  public static void main(String[] args) {
    Test test = new Test();
    test.doStuff();
  }

}
Run Code Online (Sandbox Code Playgroud)