JAVA枚举引入枚举知识点的前戏
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA枚举引入枚举知识点的前戏相关的知识,希望对你有一定的参考价值。
/* 例子:定义一个员工类Employees,使用一个变量restday来表示他哪一天休息 */ //-------------------------------version:0.1---------------------- /* class Employees { private int restday; //一周的哪一天休息 public int getRestday() { return restday; } public void setRestday(int restday) { this.restday = restday; } } public class EnumerateDemo { public static void main(String[] args) { Employees e = new Employees(); //创建员工对象 e.setRestday(2); //设置休息时间 int restday = e.getRestday(); if(restday == 6 || restday == 7) { System.out.println("周末休息..."); } else { System.out.println("周一至周五休息..."); } } } 上述代码的问题: 1、数据类型不安全 (可以传入float等) 2、数据范围不安全 (可以设置任何数字) 3、数据表示的含义不明确 (3表示什么?) */ //----------------------------version:0.2(对发现的问题进行改进)----------------------------- //定义一个星期几的常量类 /* class Weekday { public static final int Monday = 1; public static final int Tuesday = 2; public static final int Wednesday = 3; public static final int Thursday = 4; public static final int Friday = 5; public static final int Saturday = 6; public static final int Sunday = 7; } class Employees { private int restday; //一周的哪一天休息 public int getRestday() { return restday; } public void setRestday(int restday) { this.restday = restday; } } public class EnumerateDemo { public static void main(String[] args) { Employees e = new Employees(); //创建员工对象 e.setRestday(Weekday.Wednesday); //通过引用常量设置休息时间 int restday = e.getRestday(); //得到值 if(restday == 6 || restday == 7) { System.out.println("周末休息..."); } else { System.out.println("周一至周五休息..."); } } } 解决的问题: 1、数据表示的含义明确性已经提高,Monday = 1; 表示周一 依然存在问题: 1、数据类型还是不安全 2、数据范围不安全 (还是可以设置任何数字) */ //--------------------------------version:0.3-------------------------------- //将原来的常量类改写:封装成对象的方式 class Weekday { private Weekday(){}; //预防创建对象,私有化构造函数 public static final Weekday Monday = new Weekday(); //因为int类型不安全,因此改写对象,Monday变量存储的是Weekday类型的对象 public static final Weekday Tuesday = new Weekday(); public static final Weekday Wednesday = new Weekday(); public static final Weekday Thursday = new Weekday(); public static final Weekday Friday = new Weekday(); public static final Weekday Saturday = new Weekday(); public static final Weekday Sunday = new Weekday(); } class Employees { private Weekday restday; //一周的哪一天休息(数据类型为Weekday) public Weekday getRestday() { return restday; } public void setRestday(Weekday restday) //数据类型为Weekday { this.restday = restday; } } public class EnumerateDemo { public static void main(String[] args) { Employees e = new Employees(); //创建员工对象 e.setRestday(Weekday.Wednesday); //通过类名.对象的方式来设置休息时间 Weekday restday = e.getRestday(); //用Weekday类型的变量restday来接收得到的值 if(restday == Weekday.Saturday || restday == Weekday.Sunday) { System.out.println("周末休息..."); } else { System.out.println("周一至周五休息..."); } } } /*解决了的问题: 1、数据类型安全了 2、数据范围安全了*/ //--------------------version:4.(引入枚举)--------------------------------- //见JAVA枚举(二),该知识点努力更新中...
以上是关于JAVA枚举引入枚举知识点的前戏的主要内容,如果未能解决你的问题,请参考以下文章