package enumjava5;
public enum Color {
RED(255, 0, 0){
public String getMood(){
return "live";
}
},
GREEN(0, 255, 0){
public String getMood(){
return "rest";
}
},
BLUE(0, 0, 255){
public String getMood(){
return "sleep";
}
};
Integer red;
Integer green;
Integer blue;
private Color(Integer red, Integer green, Integer blue){
this.red = red;
this.green = green;
this.blue = blue;
}
public String getCode(){
return red + ", " + green + ", " + blue;
}
public abstract String getMood();
@Override
public String toString(){
return "Color #" + this.ordinal() + ", " + this.name();
}
}
- Use keyword enum -
public enum Color
- Constuctor is
private
. - You can implements yours method:
String getCode()
- You can implements yours abstract method:
abstract String getMood()
- You can use heritage method:
String name()
,int ordinal()
,<T>[] values()
,<T> valueOf(String)
package enumjava5;
public class Main {
public static void main(String[] args) {
for (Color color : Color.values()) {
System.out.println("name: " + color.name() + ", code: " + color.getCode() + ", mood: " + color.getMood() + ", asString: " + color.toString());
}
}
}
output:
name: RED, code: 255, 0, 0, mood: live, asString: Color #0, RED
name: GREEN, code: 0, 255, 0, mood: rest, asString: Color #1, GREEN
name: BLUE, code: 0, 0, 255, mood: sleep, asString: Color #2, BLUE
You can use inner enum
:
package enumjava5;
public class Outter{
public enum Color{
RED, GREEN, BLUE;
}
public static void main(String[] args){
for (Color m: Color.values()){
System.out.println( m.name() );
}
}
}