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?
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>.
Java Enum and Interface As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.
Nope. it is not possible. Enum can not inherit in derived class because by default Enum is sealed.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With