接口内部的枚举实现-Java

接口内部的枚举实现-Java,java,interface,enums,enumeration,Java,Interface,Enums,Enumeration,我有一个关于在接口中放置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(){

我有一个关于在接口中放置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();
   ...
}
我知道接口由带有空实体的方法组成。但是,我在这里使用的枚举需要一个构造函数和一个方法来获取关联的值。在本例中,建议的接口将不仅仅由具有空实体的方法组成。是否允许此实现

我不确定是应该将enum类放在接口内还是应该将实现此接口的类放在接口内


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

接口中声明
枚举
是完全合法的。在您的情况下,接口仅用作枚举的名称空间,仅此而已。无论您在哪里使用该界面,它都会正常使用。

简言之,是的,这是可以的

接口不包含任何方法体;相反,它包含您称之为“空体”的内容以及更常见的方法签名


枚举是否在接口内部并不重要。

是的,它是合法的。在“真实”的情况下,数字将实现这个东西,而这个东西可能有一个或多个空方法。

下面列出了上述东西的示例:

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

}

我知道在接口中使用enum是可以的。但我也在接口内部的枚举中创建了一个构造函数和方法。那么,接口定义还可以吗?我们可以为上述场景提供一个工作示例吗?我很困惑:(:(当然可以,包含在
枚举
中的任何内容都是它的一部分,而不是
接口
的一部分。另外一个(概念性)问题。假设可以做到这一点,假设您有一个类Impl实现它{…},在另一个类User中,Thing Thing=newimpl(…),然后您需要Number n=Thing.getNumber();-类User如何知道Number的定义?