标签:
1.垃圾数据冗余,我们要求输错了就要给提示,而不是默认!
class Person{ private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { if ("man".equalsIgnoreCase(sex) || "woman".equalsIgnoreCase(sex)) { this.sex = sex; }else{ this.sex = "man"; } } } public class EnumTest { public static void main(String[] args) { Person p = new Person(); p.setName("张三"); p.setSex("人妖"); System.out.println(p.getName()+"的性别是:"+p.getSex());//张三的性别是:man } }
2.优化 抛出异常,但是是运行时异常,我们想要的是在编译的时候就给我们提示,所以还是要继续优化...
public void setSex(String sex) { if ("man".equalsIgnoreCase(sex) || "woman".equalsIgnoreCase(sex)) { this.sex = sex; }else{ throw new RuntimeException("性别不能乱输呀"); } }
3.继续优化: Enum的雏形到来了
class Person{ 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) {//接收Gender类型 this.sex = sex ; } } class Gender{//Enum的爷爷 String gender ; private Gender(String gender){this.gender = gender;}//构造器私有化,防止别人new 对象,随意改变数据! public static final Gender MAN = new Gender("man"); public static final Gender WOMAN = new Gender("wowan"); } public class EnumTest { public static void main(String[] args) { Person p = new Person(); p.setName("张三"); p.setSex(Gender.WOMAN); System.out.println(p.getName()+"的性别是:"+p.getSex().gender);//张三的性别是:wowan } }
4.Enum到来了!春天来了...
enum Gender{ MAN("man"),WOWAN("woman"); //枚举值必须放置第一行 String gender; private Gender(String gender){this.gender = gender;} } public class EnumTest { public static void main(String[] args) { Person p = new Person(); p.setName("张三"); p.setSex(Gender.MAN); System.out.println(p.getName()+"的性别是:"+p.getSex().gender);//张三的性别是:man } }
5.enum注意事项:
标签:
原文地址:http://www.cnblogs.com/bravolove/p/5851467.html