CNB CNB - 24 days ago 9
Java Question

error while declaring enum within an interface

The idea is to create an interface consiting of an enum that would hold county codes so I can use it later as a value for a variable in objects.

It supposed to be something like:

public interface CountrCodes {

public enum Countries { france(FR), germany(D), spain(ES), portugal(PT)};

}


But it IDE (Eclipse) is arguing with me that:

> 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


It's my irst time with enums and I am confused as I thought it was absolutely legal and correct to use enum within an interface. How can I make it work?

Answer

What you are trying to do, is called an inner enum. A enum which is inside a class, nothing fancy, and nothing complex. Totally legal. Also commons as inner classes. But in this case, it is an enum.

An enum is another kind of object, like classes, but they have some other properties. For example, enum are thread safe and they are serializable.

You particular example has no issues. It doesn't compiles, because the compiler can not resolve FR, D, ES and PT. If I remove those country codes, it compiles using Java 8.

For more references, take a look here:

https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

Comments