Java 枚举(定义其它结构)

范例1:扩充枚举功能

enum Color {
	RED("红色"),GREEN("绿色"),BLUE("蓝色");
	private String title;
	private Color(String title) {
		this.title=title;
	}
	@Override
	public String toString() {
		return this.title;
	}
	
}

public class Demo {
	public static void main(String[] args) {
		for (Color c : Color.values()) {
			System.out.println(c.ordinal() + "-" + c.name());
		}
	}

}

Java 枚举(定义其它结构)_第1张图片

=============分割线=============

范例2:枚举实现接口

interface Message {
	public String getTitle();
}

enum Color implements Message {
	RED("红色"), GREEN("绿色"), BLUE("蓝色");
	private String title;

	private Color(String title) {
		this.title = title;
	}

	@Override
	public String getTitle() {
		return this.title;
	}

	@Override
	public String toString() {
		return this.title;
	}

}

public class Demo {
	public static void main(String[] args) {
		Message msg = Color.BLUE;
		System.out.println(msg.getTitle());
	}

}

=============分割线=============

范例3:另一种接口实现

interface Message {
	public String getTitle();
}

enum Color implements Message {
	RED("红色") {
		public String getTitle() {
			return "自己的" + this;
		}
	},
	GREEN("绿色") {
		public String getTitle() {
			return "自己的" + this;
		}
	},
	BLUE("蓝色") {
		public String getTitle() {
			return "自己的" + this;
		}
	};

	private String title;

	private Color(String title) {
		this.title = title;
	}

	@Override
	public String toString() {
		return this.title;
	}

}

public class Demo {
	public static void main(String[] args) {
		Message msg = Color.BLUE;
		System.out.println(msg.getTitle());
	}

}

=============分割线=============

范例4:枚举内定义抽象方法

enum Color {
	RED("红色") {
		public String getTitle() {
			return "自己的" + this;
		}
	},
	GREEN("绿色") {
		public String getTitle() {
			return "自己的" + this;
		}
	},
	BLUE("蓝色") {
		public String getTitle() {
			return "自己的" + this;
		}
	};

	private String title;

	private Color(String title) {
		this.title = title;
	}

	@Override
	public String toString() {
		return this.title;
	}

	public abstract String getTitle();
}

public class Demo {
	public static void main(String[] args) {
		Color c = Color.GREEN;
		System.out.println(c.getTitle());
	}

}


你可能感兴趣的:(Java,枚举)