标签:set value enum main log 使用 static etag 私有化
1..创建一个Student实体类
public class Student {
private String name; //姓名
private Gender sex; //性别 类型是个枚举
private int age;
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
public Student() {
super();
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2.创建对应的枚举类
/** 枚举类 (像类 又像数组)
* 01.只能有私有化的构造方法! 外部不能访问!
* 02.所有的枚举值都是public static final
*/
public enum Gender {
//枚举值 静态常量大写
MAN(1,"男"),WOMAN(0,"女");
private int index;
private String sex;
private Gender(int index,String sex){
this.index=index;
this.sex=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;
}
}
3.创建测试类
public class EnumTest {
public static void main(String[] args) {
//创建一个Student对象
Student student=new Student();
/*
*想避免不健康的输入
*01.使用set() 做判断
*02.使用枚举 :规范了参数的类型
*/
student.setSex(Gender.MAN);
System.out.println("学生的性别是:"+student.getSex());
//遍历枚举中的数据
for (Gender g : Gender.values()) {
System.out.println(g.getSex());
}
}
}
标签:set value enum main log 使用 static etag 私有化
原文地址:http://www.cnblogs.com/HHR-SUN/p/7015673.html