枚举类型介绍
Java中对常量数据的配置可以使用枚举类型实现,枚举类型是面向对象、属性、方法等所有它非常方便定义,枚举类型将它的对象设置为常量方便读取和使用。
\\定义枚举类型要用关键字enum
public enum 枚举类名{
枚举项1,枚举项2,枚举项3.....;
构造方法
成员变量
成员方法
}
1.每个枚举类型继承java.lang.Enum,所以枚举类不能再继承其它类型
2、枚举项就是枚举类型的对象,一般使用大写字母,一个枚举项表示一个常量项,多个枚举项中间用逗号分隔。
3、枚举类型的构造方法使用private私有
4、通过“枚举类名,枚举项名称”去访问指定的枚举项
public enum PayEnum {
//枚举项就是一个一个对象,它是常量
WEIXINPAY("weixin","https://api.mch.weixin.qq.com/pay/"),
ALIAPY("ali","https://openapi.alipay.com/"),
UNIONPAY("union","https://gateway.95516.com/gateway/api/");
private String name;
private String payUrl;
//枚举类型的构造方法是private
private PayEnum(){
}
private PayEnum(String name, String payUrl){
this.name = name;
this.payUrl = payUrl;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getPayUrl(){
return payUrl;
}
public void setPayUrl(String payUrl){
this.payUrl = payUrl;
}
public static void main(String[] args){
//枚举项就是一个对象(实例)
PayEnum weixinPay = PayEnum.WEIXINPAY;
System.out.println(PayEnum.WEIXINPAY.getName());
PayEnum aliPay = PayEnum.ALIAPY;
System.out.println(aliPay == PayEnum.ALIAPY);
}
}
public interface SystemCode {
int getCode();
String getDesc();
}
public enum CodeEnum implements SystemCode{
ERROR(-1,"操作成功"),
FAILURE(0,"操作失败"),
SUCCESSFUL(1,"操作成功"),
LOGINSUCCESSFUL(100,"登入成功");
private CodeEnum(int code, String desc){
this.code = code;
this.desc = desc;
}
int code;
String desc;
@Override
public int getCode() {
return code;
}
@Override
public String getDesc() {
return desc;
}
public static void main(String[] args){
System.out.println(CodeEnum.SUCCESSFUL.getCode());
System.out.println(CodeEnum.SUCCESSFUL.getDesc());
SystemCode code = CodeEnum.SUCCESSFUL;
System.out.println(code.getCode());
System.out.println(code.getDesc());
}
}
1
操作成功
1
操作成功
weixin
true