1、创建枚举类
使用ENUM来修饰
2、构建属性
private String name;
private String age;
private String color;
3、创建构造函数
private ShowFar(String name, String age,String color) {
this.name = name;
this.age = age;
this.color=color;
}
4、根据构造函数,来创建枚举值;例如构造函数中有三个参数,所以枚举值也必须配置三个参数,否则编译不通过
ALL_CAN("1111","222","333") 正确,
ALL_PGN("2222","333","444") 正确,
ALL_UDS("2222","333") 错误;
若想让枚举类型ALL_UDS正确,则需要构建一个两个参数的构造函数,如下
private ShowFar(String name, String age) {
this.name = name;
this.age = age;
}若想让枚举类型ALL_UDS正确,则需要构建一个两个参数的构造函数,如下
private ShowFar(String name, String age) {
this.name = name;
this.age = age;
}
构建之后
ALL_CAN("1111","222","333") 正确,
ALL_PGN("2222","333","444") 正确,
ALL_UDS("2222","333") 正确;
5、使用枚举值
ShowFar ert=ShowFar.ALL_CAN;
上面的代码,相当于调用了ShowFar(String name, String age,String color)这个构造函数,并将ALL_CAN枚举值的三个参数依次传值给name,age,color
ShowFar ert=ShowFar.ALL_UDS;
上面的代码,相当于调用了ShowFar(String name, String age)这个构造函数,并将ALL_CAN枚举值的三个参数依次传值给name,age
上面两个调用,返回的都是枚举类实例;
下面是完整代码段:
public enum ShowFar {
ALL_CAN("1111","222","333"),
ALL_PGN("2222","333","444"),
ALL_UDS("2222","333");
private String name;
private String age;
private String color;
private ShowFar(String name, String age,String color) {
this.name = name;
this.age = age;
this.color=color;
}
private ShowFar(String name, String age) {
this.name = name;
this.age = age;
}
}