简体   繁体   English

接口内部的枚举实现 - Java

[英]enum implementation inside interface - Java

I have a question about putting a Java enum in the interface. 我有一个关于在界面中放置Java枚举的问题。 To make it clearer, please see the following code: 为了更清楚,请参阅以下代码:

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

I know that an interface consists of methods with empty bodies . 我知道接口包含空体的方法。 However, the enum I used here needs a constructor and a method to get an associated value. 但是,我在这里使用的枚举需要一个构造函数和一个方法来获取相关的值。 In this example, the proposed interface will not just consist of methods with empty bodies. 在此示例中,建议的接口不仅包含具有空体的方法。 Is this implementation allowed? 是否允许此实施?

I am not sure if I should put the enum class inside the interface or the class that implements this interface. 我不确定是否应该将enum类放在接口或实现此接口的类中。

If I put the enum in the class that implements this interface, then the method public Number getNumber() needs to return the type of enum, which would force me to import the enum in the interface. 如果我将枚举放在实现此接口的类中,那么public Number getNumber()方法需要返回枚举类型,这将迫使我在接口中导入枚举。

It's perfectly legal to have an enum declared inside an interface . interface声明enum是完全合法的。 In your situation the interface is just used as a namespace for the enum and nothing more. 在您的情况下,接口仅用作枚举的命名空间,仅此而已。 The interface is used normally wherever you use it. 无论您在何处使用,都可以正常使用该界面。

Example for the Above Things are listed below : 以下列出了以上事项的示例:

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

}

In short, yes, this is okay. 简而言之,是的,这没关系。

The interface does not contain any method bodies; 该接口不包含任何方法体; instead, it contains what you refer to as "empty bodies" and more commonly known as method signatures . 相反,它包含您所称的“空体”,通常称为方法签名

It does not matter that the enum is inside the interface. enum在界面内部并不重要。

Yes, it is legal. 是的,这是合法的。 In a "real" situation Number would implement Thing, and Thing would probably have one or more empty methods. 在“真实”的情况下,Number会实现Thing,而Thing可能会有一个或多个空方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM