枚举实现在界面 - Java [英] enum implementation inside interface - Java

查看:91
本文介绍了枚举实现在界面 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  public interface Thing {
public enum Number {
一(1),二(2),三(3);
private int value;
private Number(int value){
this.value = value;
}
public int getValue(){
返回值;
}
}

public Number getNumber();
public void method2();
...
}

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



我不知道我是否应该将枚举类放在接口或实现此接口的类中。



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

解决方案

有一个枚举是非常合法的界面中声明。在您的情况下,该界面仅用作枚举的命名空间,而没有更多。该界面通常用于任何地方。


I have a question about putting a Java enum in the interface. 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.

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.

解决方案

It's perfectly legal to have an enum declared inside an interface. 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.

这篇关于枚举实现在界面 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆