Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java enums from different classes?

Tags:

java

enums

class

If I had a class in Java like this:

public class Test {     // ...     public enum Status {         Opened,         Closed,         Waiting     }     // ... } 

And I had a different class in a different class file (but in the same project/folder):

public class UsingEnums {     public static void Main(String[] args)     {         Test test = new Test(); // new Test object (storing enum)          switch(test.getStatus()) // returns the current status         {             case Status.Opened:                 // do something             // break and other cases         }     } } 

I would effectively have an enum in one class that is used in another class (in my case, specifically in a switch-case statement).

However, when I do that, I get an error like:

cannot find symbol - class Status

How would I fix that?

like image 541
Bhaxy Avatar asked Dec 12 '11 22:12

Bhaxy


People also ask

Can you nest enums in Java?

Department enum defined above is a nested enum type as it is 'nested' inside another class. Nested enum types are implicitly static, and hence mentioning static in their definition is actually redundant. An enum constant of static nested enum Department type can be accessed using the syntax – <enclosing-class-name>.

Can enums be inherited Java?

Java Enum and Interface As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.

Can enums be inherited?

Nope. it is not possible. Enum can not inherit in derived class because by default Enum is sealed.


1 Answers

An enum switch case label must be the unqualified name of an enum constant:

switch (test.getStatus()) // returns the current status {     case Opened:         // do something         // break and other cases } 

It doesn't matter that it's defined within another class. In any case, the compiler is able to infer the type of the enum based on your switch statement, and doesn't need the constant names to be qualified. For whatever reason, using qualified names is invalid syntax.

This requirement is specified by JLS §14.11:

SwitchLabel:    case ConstantExpression :    case EnumConstantName :    default :  EnumConstantName:    Identifier 

(Thanks to Mark Peters' related post for the reference.)

like image 95
Paul Bellora Avatar answered Sep 21 '22 11:09

Paul Bellora