1、定义步骤:
enum EnumTest {
//1、提供当前枚举类的对象
//格式:对象名1(属性1, 属性2, ...),
// 对象名2(属性1, 属性2, ...),
// 对象名3(属性1, 属性2, ...);
STUDENT("学生", 0),
TEACHER("老师", 8000),
PRESIDENT("校长", 10000);
//2、声明EnumTest对象属性,注意用 private final 进行修饰
private final String name;
private final double salary;
//3、私有化构造器,并对属性赋值
private EnumTest(String name, double salary) {
this.name = name;
this.salary = salary;
}
//对toString()方法重写
// @Override
// public String toString() {
// return "EnumTest{" +
// "name='" + name + '\'' +
// ", salary=" + salary +
// '}';
// }
}
public class EnumTestMain {
public static void main(String[] args) {
EnumTest student = EnumTest.STUDENT;
System.out.println(student);
System.out.println("----------------------------");
//values()方法:返回所有的枚举类对象构成的数组
EnumTest[] values = EnumTest.values();
for (EnumTest value : values) {
System.out.println(value);
}
}
}
测试结果(不进行 toString() 方法重写):
测试结果(对 toString() 方法重写):
2、枚举类对象分别实现接口
interface Explain {
void vocationExplain();
}
enum EnumTest implements Explain{
STUDENT("学生", 0){
@Override
public void vocationExplain() {
System.out.println("学生要努力学习");
}
},
TEACHER("老师", 8000) {
@Override
public void vocationExplain() {
System.out.println("老师要教书育人");
}
},
PRESIDENT("校长", 10000) {
@Override
public void vocationExplain() {
System.out.println("校长要管理学校事务");
}
};
private final String name;
private final double salary;
private EnumTest(String name, double salary) {
this.name = name;
this.salary = salary;
}
}
public class EnumTestMain {
public static void main(String[] args) {
EnumTest student = EnumTest.STUDENT;
EnumTest teacher = EnumTest.TEACHER;
EnumTest president = EnumTest.PRESIDENT;
student.vocationExplain();
teacher.vocationExplain();
president.vocationExplain();
}
}
测试结果