这个想法是创建一个由枚举组成的接口(interface),该枚举将保存县代码,以便我稍后可以将其用作对象中变量的值。
它应该是这样的:
public interface CountrCodes {
public enum Countries { france(FR), germany(D), spain(ES), portugal(PT)};
}
但 IDE (Eclipse) 与我争论:
> Syntax error, insert ")" to complete Expression
> - 'enum' should not be used as an identifier, since it is a reserved keyword from source level 1.5 on
> - enum cannot be resolved to a type
> - PT cannot be resolved to a variable
> - ES cannot be resolved to a variable
> - Syntax error on token ")", delete this token
> - Syntax error, insert ";" to complete BlockStatements
> - D cannot be resolved to a variable
> - Syntax error, insert ";" to complete FieldDeclaration
> - F cannot be resolved to a variable
这是我第一次使用枚举,我很困惑,因为我认为在接口(interface)中使用枚举是绝对合法且正确的。我怎样才能让它发挥作用?
最佳答案
我无法确切地说接口(interface)声明何时可以具有嵌套成员,但至少从 Java 7 开始,嵌套成员是可能的。
如果您定义了一个接口(interface),其中一组常量主要可与该接口(interface)一起使用,那么将这些常量作为枚举类嵌套在该接口(interface)中可能会很方便。这是一个完全可以接受的接口(interface)用例。考虑您自己的代码:
public interface CountryCodes {
public enum Countries { france(FR), germany(D), spain(ES), portugal(PT)};
}
很明显,您希望将枚举类 Countries
嵌套在接口(interface) CountryCodes
中(因为单个枚举常量是单个事物,所以我建议不要使用复数形式)用于枚举类名称,例如 Country.SPAIN
而不是 Countries.SPAIN
;按照惯例,枚举常量也应全部大写命名)。
但是,您的声明的不同之处在于您明确希望将数据与常量关联起来。因此,您的枚举类需要一个实例字段和一个构造函数:
public interface CountryCodes {
public static enum Country {
FRANCE("FR"),
GERMANY("DE"),
SPAIN("ES"),
PORTUGAL("PT");
private final String e_countryId;
private Country(String c) {
this.e_countryId = c;
}
}
:
:
}
枚举类声明中的指定static
是不必要的。我喜欢包含它以明确枚举是嵌套成员。
关于java - 在接口(interface)中声明枚举时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40553031/