Java枚举定义
枚举值定义,在构造方法赋值,重写toString();
测试类
package com.yjm.test; enum TestEnum { ye("yellow"),re("red"),gr("green"); private String str; public String getStr() { return this.str; } public void setStr(String str) { this.str = str; } TestEnum(String str){ this.str=str; } @Override public String toString() { return this.getStr(); }; } enum TestEnum1 { ye("yellow"),re("red"),gr("green"); private String str; public String getStr() { return this.str; } public void setStr(String str) { this.str = str; } TestEnum1(String str){ this.str=str; } //区别上边枚举无重写toString方法 // @Override // public String toString() { // return this.getStr(); // }; } enum TestEnum2 { ye("yellow",1),re("red",2),gr("green",3); private String str; private int i; public int getI() { return i; } public void setI(int i) { this.i = i; } public String getStr() { return this.str; } public void setStr(String str) { this.str = str; } TestEnum2(String str,int i){ this.str=str; this.i=i; } //区别上边枚举无重写toString方法 // @Override // public String toString() { // return this.getStr()+this.i; // }; } enum TestEnum3 { ye("yellow",1),re("red",2),gr("green",3); private String str; private int i; public int getI() { return i; } public void setI(int i) { this.i = i; } public String getStr() { return this.str; } public void setStr(String str) { this.str = str; } TestEnum3(String str,int i){ this.str=str; this.i=i; } //区别上边枚举无重写toString方法 @Override public String toString() { return this.getStr()+this.i; }; } enum TestEnum4 { yellow,red,green; } public class TestEn{ public static void main(String[] args) { System.out.println("enum: "+TestEnum.ye); System.out.println("enum1: "+TestEnum1.ye); System.out.println("enum2: "+TestEnum2.ye); System.out.println("enum3: "+TestEnum3.ye); System.out.println("enum4: "+TestEnum4.green); } }
测试输出结果:
enum: yellow
enum1: ye
enum2: ye
enum3: yellow1
enum4: green
枚举不重写toString方法输出自身值,如果枚举值里面有值对 ,则需要在构造方法里进行传值,构造。
原文:http://yjm199.blog.51cto.com/4408395/1681956