Java的枚举类型本质上是属于多例设计模式,所以构造方法要使用private来修饰。
普通定义和使用:
public class EnumTest {
public static void main(String[] args) {
for (Color color : Color.values()){
System.out.println(color);
}
}
}
enum Color{
RED("红色"),GREEN("绿色"),Blue("蓝色"),YELLOW("黄色");
private String title;
private Color(String title){
this.title = title;
}
@Override
public String toString() {
return title;
}
}
实现接口使用:
public class EnumTest {
public static void main(String[] args) {
for (Color color : Color.values()){
System.out.println(color.getMessage());
}
}
}
interface Message{
String getMessage();
}
enum Color implements Message{
RED("红色"),GREEN("绿色"),Blue("蓝色"),YELLOW("黄色");
private String title;
private Color(String title){
this.title = title;
}
@Override
public String toString() {
return title;
}
@Override
public String getMessage() {
return title;
}
}
枚举类型内定义抽象方法:
public class EnumTest {
public static void main(String[] args) {
for (Color color : Color.values()){
System.out.println(color.getString());
}
}
}
interface Message{
String getMessage();
}
enum Color implements Message{
RED("红色"){
@Override
public String getString() {
return this.name() + this.getMessage();
}
},GREEN("绿色"){
@Override
public String getString() {
return this.name() + this.getMessage();
}
},Blue("蓝色"){
@Override
public String getString() {
return this.name() + this.getMessage();
}
},YELLOW("黄色"){
@Override
public String getString() {
return this.name() + this.getMessage();
}
};
private String title;
private Color(String title){
this.title = title;
}
@Override
public String toString() {
return title;
}
@Override
public String getMessage() {
return title;
}
//枚举类型内定义抽象方法
public abstract String getString();
}
网友评论