Say I have an Enum as follows:
package stackoverflow.models;
public enum MyEnum {
VALUE_1,
VALUE_2;
}
And then I have a POJO which has this Enum as 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, should I do a switch
on MyPojo.getMyEnum()
, I do not need to import the 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 was just wondering why this is? How does Java resolve the Enum values if it doesn't import the Enum directly?
An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default. enum constants are accessed using dot syntax. An enum class can have attributes and methods, in addition to constants.
Java Enum and Interface As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.
In Java (from 1.5), enums are represented using enum data type. Java enums are more powerful than C/C++ enums. In Java, we can also add variables, methods, and constructors to it. The main objective of enum is to define our own data types(Enumerated Data Types).
An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).
It's not the enum type itself but the enum constants, where the scope include case
labels of a switch
statement, as mentioned in this section of the Java Language Specification:
The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is visible (§6.4.1).
...
The scope of an enum constant C declared in an enum type T is the body of T, and any case label of a
switch
statement whose expression is of enum type T (§14.11).
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