您可以将枚举用于相同的目的,这将限制您仅使用指定的值.
按如下方式声明您的部门枚举
public enum Department {
Accounting, Marketting, Human_Resources, Information_Systems
}
您现在可以使用Employee类
public class Employee {
String name;
int age;
Department department;
Employee(String name, int age, Department department) {
this.name = name;
this.age = age;
this.department = department;
}
int getAge() {
return age;
}
}
在创建员工时,您可以使用
Employee employee = new Employee("Prasad", 47, Department.Information_Systems);
按照Adrian Shum的建议进行编辑,当然因为这是一个很好的建议.
>枚举是常量,这就是为什么根据java惯例以大写字母声明它的好处.
>但我们不希望看到枚举的大写字母,因此我们可以创建枚举构造函数并将可读信息传递给它.
>我们将修改枚举以包含toString()方法和带有字符串参数的构造函数.
public enum Department {
ACCOUNTING("Accounting"), MARKETTING("Marketting"), HUMAN_RESOURCES(
"Human Resources"), INFORMATION_SYSTEMS("Information Systems");
private String deptName;
Department(String deptName) {
this.deptName = deptName;
}
@Override
public String toString() {
return this.deptName;
}
}
因此,当我们按如下方式创建Employee对象并使用它时,
Employee employee = new Employee("Prasad Kharkar", 47, Department.INFORMATION_SYSTEMS);
System.out.println(employee.getDepartment());
我们将获得一个可读的字符串表示形式作为信息系统,因为它由toString()方法返回,该方法由System.out.println()语句隐式调用.
阅读关于Enumerations的好教程