enum implementation inside interface - Java

元气小坏坏 提交于 2019-12-02 21:56:11

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.

MaheshB

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.

Yes, it is legal. In a "real" situation Number would implement Thing, and Thing would probably have one or more empty methods.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!