1.枚举类
01.限定用户的输入
02.所有的枚举 值都是static final修饰的(静态常量)
03.构造必须是私有的,防止外部访问
2.为了防止用户不健康的输入
使用enum:
01.创建一个枚举类
02.创建枚举值
03.把需要限定的属性的类型改成枚举类即可
3.创建一个Student实体类
public class Student { private String name;// 姓名 private Gender sex;// 性别 public String getName() { return name; } public void setName(String name) { this.name = name; } public Gender getSex() { return sex; } public void setSex(Gender sex) { this.sex = sex; } public Student(String name, Gender sex) { super(); this.name = name; this.sex = sex; } @Override public String toString() { return "Student [name=" + name + ", sex=" + sex + "]"; } public Student() { super(); }
4.创建一个性别的enum类
public enum Gender { Man(1, "男"), Woman(0, "女"); private int index; private String sex; public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } private Gender(int index, String sex) { this.index = index; this.sex = sex; }
5.测试类
Student stu = new Student(); stu.setName("haha"); stu.setSex(Gender.Man); System.out.println("学生的性别是:" + stu.getSex()); for (Gender g : Gender.values()) { System.out.println(g.getSex()); }