Java compilation error: switch on enum

后端 未结 3 1241
梦谈多话
梦谈多话 2021-01-20 17:54

I came across a very weird error that I just can\'t figure out how to solve.

A project, that compiles just fine on Windows, doesn\'t compile on Linux with the follow

3条回答
  •  星月不相逢
    2021-01-20 18:32

    I don't know whether it is windows/linux related issue. But

    From jdk5 onwards you can use enum in switch case and from jdk7 you can use String in switch case. While using enum in switch make sure that:

    1. you are using jdk5 and later
    2. All the labels used in your switch must be a valid enum object inside your enum being used in switch.

    In java enum is implemented through class concept(Each n every enum in java extends to Enum class that is an abstract class and direct sub class of Object class). So while creating enum like

     public enum Bbb {
            ONE,
            TWO;
        }
    

    It will internally meant

    public static final Bbb ONE=new Bbb();
    public static final Bbb TWO=new Bbb();
    

    Means all your defined enum objects are public, final and static objects of defined enum class. If you are using something else as switch label, it will give a compile time error.

    For each enum in java, super class Enum is final and all enum classes are internally implemented as final. So inheritance can not be used for enum in java. Means we are not allowed to use anything else in switch labels except our own class enum objects(Not even subclass objects, because enum class can't be inherited further)

提交回复
热议问题