猿问

在Java中开启Enum

为什么不能打开Java枚举?看起来很简单,可以编写一些方便的代码。这个问题也适用于String。您可以打开char,但不能打开String...?



温温酱
浏览 385回答 3
3回答

慕哥9229398

实际上,您可以switch使用enums,但是直到Java 7才可以switch使用Strings。您可以考虑将Java enum的多态方法分派使用,而不是显式switch。请注意,enums是Java中的对象,而不仅仅是ints的符号,就像在C / C ++中一样。您可以在enum类型上有一个方法,然后不用编写a switch,只需调用该方法-一行代码即可:完成!enum MyEnum {    SOME_ENUM_CONSTANT {        @Override        public void method() {            System.out.println("first enum constant behavior!");        }    },    ANOTHER_ENUM_CONSTANT {        @Override        public void method() {            System.out.println("second enum constant behavior!");        }    }; // note the semi-colon after the final constant, not just a comma!    public abstract void method(); // could also be in an interface that MyEnum implements}void aMethodSomewhere(final MyEnum e) {    doSomeStuff();    e.method(); // here is where the switch would be, now it's one line of code!    doSomeOtherStuff();}
随时随地看视频慕课网APP

相关分类

Java
我要回答