Enable Enum Does Not Import Class

Say I have an Enum as follows:

package stackoverflow.models; public enum MyEnum { VALUE_1, VALUE_2; } 

And then I have a POJO in which this Enum is one of its fields:

 package stackoverflow.models; public class MyPojo { private MyEnum myEnum; public MyEnum getMyEnum() { return myEnum; } public void setMyEnum(MyEnum myEnum) { this.myEnum = myEnum; } } 

Now, if I have to make a switch on MyPojo.getMyEnum() , I need not to import Enum directly into my class:

 package stackoverflow.classes; import stackoverflow.models.MyPojo; public class MyClass { public static void main(final String... args) { final MyPojo pojo = new MyPojo(); switch(pojo.getMyEnum()) { case VALUE_1: break; case VALUE_2: break; default: break; } } } 

I'm just wondering why that is? How does Java resolve Enum values ​​if it does not import Enum directly?

+5
source share
1 answer

This is not the type of enumeration itself, but enumeration constants, where the scope includes case labels for the switch , as described in this section of the Java Language Specification :

The scope of the declaration is the area of ​​the program within which the entity declared by the declaration can refer to a simple name provided that it is visible (§6.4.1).

...

The scope of the enumeration constant C declared in the enumeration type T is the body of T and any case label of the switch whose expression has the enumeration type T (§14.11).

+5
source

Source: https://habr.com/ru/post/1244670/


All Articles