之前没有用过枚举,不懂。今天找了些资料学习了,现在总结如下:(希望高手看到后批评指教)
枚举的作用:
1、限定某一类型的取值范围。
2.不再写public static final...(如果取值范围太广,就太麻烦了),但最终enum还是要转化成class类型,还是会加public
static final...
一段代码说明为什么java要有enum类型:
package good.good.study;public class EnumStudy2 {
public static void main(String[] args) {
/**
* Person1(...)和 Person2(...)不合理 ;Person3(...)有点麻烦
*
*/
new Person1("name","male");new Person1("name2", "name2");//字符串类型的数据可以随便填,不会报错,但是不合理!
new Person2("name", true);//true 代表什么啊?不明确
new Person3("name",Sex.MALE);//public static final
new Person4("name",Sex_enum.MALE);//enum
}
}
class Person1{private String name;
private String sex;public Person1(String name,String sex){
this.name = name;
this.sex = sex;
}}
class Person2{private String name ;
private boolean sex;public Person2(String name,boolean sex){
this.name = name;
this.sex = sex;
}
}
class Sex{private String sex;
public static final Sex MALE = new Sex("男");
public static final Sex FEMALE = new Sex("女");private Sex(String sex){
this.sex = sex;
}
}
class Person3{private String name;
private Sex sex;public Person3(String name,Sex sex){
this.name = name;
this.sex = sex;
}
}
class Person4{private String name;
private Sex_enum sex;public Person4(String name,Sex_enum sex){
this.name = name;
this.sex = sex;
}
}
enum Sex_enum{
MALE("男"),FEMALE("女");private Sex_enum(String sex){
}
}
原因就是上面的1和2
再来一段代码说明enum的基本用法:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
|
java 枚举(enum)学习,布布扣,bubuko.com