界面内部的枚举实现 – Java

我有一个关于在界面中放置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()方法需要返回枚举类型,这将迫使我在接口中导入枚举。

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

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

 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在界面内部并不重要。

是的,这是合法的。 在“真实”的情况下,Number会实现Thing,而Thing可能会有一个或多个空方法。