定义:枚举是指由一组固定的常量组成的类型。
好处:类型安全,易于输入,代码清晰。
例子:输入学生的性别只允许输入“男”或”女“。
SexEnum.java
package com.yh.myEnum; public enum SexEnum { 男,女 }
Students.java
package com.yh.myEnum; public class Students { private String name; private SexEnum sex; public Students() {} public Students(String name,SexEnum sex) { this.setName(name); } public String getName() { return name; } public void setName(String name) { this.name = name; } public SexEnum getSex() { return sex; } public void setSex(SexEnum sex) { this.sex = sex; } }
TestStudent.java
package com.yh.myEnum; public class TestStudent { public static void main(String[] args) { // TODO Auto-generated method stub Students stu1 = new Students("stu1",SexEnum.女); System.out.println(stu1.getSex()); } }