枚举
枚举是高级的多例设计模式。
枚举对象必须放在首行,随后才可以定义属性,构造,方法。枚举中定义的构造方法不能使用 public ,因为构造方法必须私有化。
enum 是一个关键字,Enum 是一个抽象类。
使用 enum 定义的枚举就相当于一个继承 Enum 的类。
enum Color{
RED,BLUE,GREEN;
}
public class Main {
public static void main(String[] args) {
Color red = Color.RED;
System.
out.println(red);
for(Color color : Color.values()){
System.
out.println(color.ordinal() +
" " + color.name());
}
}
}
枚举实现接口
interface IMessage{
String getTitle();
}
enum Color implements IMessage{
RED(
"red"),BLUE(
"blue"),GREEN(
"green");
private String title;
private Color(String title){
this.title = title;
}
public String
getTitle() {
return this.title;
}
public String
toString() {
return this.title;
}
}
public class Main {
public static void main(String[] args) {
IMessage iMessage = Color.RED;
System.
out.println(iMessage.getTitle());
}
}
枚举的实际应用
enum Sex{
MALE(
"male"),FEMALE(
"female");
private String title;
private Sex(String title){
this.title = title;
}
public String
toString() {
return this.title;
}
}
class Persion{
private String name;
private int age;
private Sex sex;
public Persion(String name,
int age, Sex sex){
this.name = name;
this.age = age;
this.sex = sex;
}
public String
toString() {
return this.name +
" " +
this.age +
" " +
this.sex;
}
}
public class Main {
public static void main(String[] args) {
Persion persion =
new Persion(
"tom",
18,Sex.MALE);
System.
out.println(persion);
}
}