Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch on Enum does not import class

Tags:

java

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?

like image 767
Dan W Avatar asked Mar 08 '16 16:03

Dan W


People also ask

Can you use switch with enum?

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.

Can enum inherit Java?

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

Can we import enum in Java?

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).

Can enum be a class?

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).


1 Answers

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).

like image 136
M A Avatar answered Oct 16 '22 02:10

M A