20180412 java java面向对象-引入枚举类型和枚举的模拟
//需求:定义一个员工类Employee,使用一个变量restday来表示他哪一天休息(一周当中的哪一天)
class Employee
{
private int restday;//一周的哪一天休息
public int getRestday()
{
return restday;
}
public void setRestday(int restday)
{
this.restday = restday;
}
}
//枚举的引入
class EnumDemo
{
public static void main(String[] args)
{
//创建一个员工对象,并设置他那一天休息
Employee e = new Employee();
e.setRestday(3);//接受int类型的值
/* 批判这里使用的int类型:
1、使用int类型来表示星期几类型不安全,
完全可以设置 非[1,7] 的数字
2、业务含义不明确,设置1表示周几(周一还是周日)
*/
int restday = e.getRestday();
if(restday == 6 || restday == 7)
{
System.out.println("这个人周末休息");
}
else
{
System.out.println("这个人不是周末休息");
}
}
}
e.setRestday(3); 这个语句的更正写法:
专门使用一个Weekday类来表示周一到周日,使用7个常量来表示。
即:
class Weekday
{
public satic final int Mon = 1;
public satic final int Tues = 2;
public satic final int Wed = 3;
public satic final int Thur = 4;
public satic final int Fri = 5;
public satic final int Sat = 6;
public satic final int Sun = 7;
}
class Employee
{
private int restday;//一周的哪一天休息
public int getRestday()
{
return restday;
}
public void setRestday(int restday)
{
this.restday = restday;
}
}
//枚举的引入
class EnumDemo
{
public static void main(String[] args)
{
//创建一个员工对象,并设置他那一天休息
Employee e = new Employee();
e.setRestday(Weekday.Wed);//周三
/*
此时业务含义很明确,Wed就表示周三的意思。
但是又因为在Employee中的restday是int类型,
我们依然可以随意设置其值,
即 e.setRestday(-1); 原则上也正确。所以还
是没有解决数据类型不安全的问题。
*/
int restday = e.getRestday();
if(restday == 6 || restday == 7)
{
System.out.println("这个人周末休息");
}
else
{
System.out.println("这个人不是周末休息");
}
}
}
为了解决数据类型不安全的问题,我们采用以下写法:
class Weekday
{
private Weekday();//构造器私有化,不让外界构造任何 新的Weekday对象。
public satic final Weekday Mon = new Weekday();
public satic final Weekday Tues = new Weekday();
public satic final Weekday Wed = new Weekday();
public satic final Weekday Thur = new Weekday();
public satic final Weekday Fri = new Weekday();
public satic final Weekday Sat = new Weekday();
public satic final Weekday Sun = new Weekday();
}
class Employee
{
private Weekday restday;//一周的哪一天休息
public Weekday getRestday()
{
return restday;
}
public void setRestday(Weekday restday)
{
this.restday = restday;
}
}
//枚举的引入
class EnumDemo
{
public static void main(String[] args)
{
//创建一个员工对象,并设置他那一天休息
Employee e = new Employee();
e.setRestday(Weekday.Wed);//周三
//e.setRestday(Weekday.Wed);//这里不能创建周八,因为构造器已经被私有化了
Weekday restday = e.getRestday();
if(restday == Weekday.Sat || restday == Weekday.Sun)
{
System.out.println("这个人周末休息");
}
else
{
System.out.println("这个人不是周末休息");
}
}
}
因为int类型不安全,我们把休息日使用一个对象类型来表示周一到周日,并固定该休息日的值只能是周一到周日。