10.11 定义枚举结构

demo1 在枚举类中定义成员属性与方法


enum Color {		// 枚举类
	RED("红色"),GREEN("绿色"),BLUE("蓝色");	// 枚举对象要写在首行
	private String title;// 成员属性
	private Color(String title){// 构造方法初始化属性;
		this.title = title;
	}

	@Override
	public String toString(){// 对象的输出都调用toString方法
		return this.title;
	}
}

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

	}
}
  • 结果
0-RED~~红色
1-GREEN~~绿色
2-BLUE~~蓝色

demo2 通过枚举类实现接口


interface IMessage {
	public String getMessage();
}

enum Color implements IMessage{		// 枚举类实现接口
	RED("红色"),GREEN("绿色"),BLUE("蓝色");	// 枚举对象要写在首行
	private String title;// 成员属性
	private Color(String title){// 构造方法初始化属性;
		this.title = title;
	}

	@Override
	public String toString(){// 对象的输出都调用toString方法
		return this.title;
	}

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

public class JavaDemo {
	public static void main(String args[]) {
		IMessage msg = Color.RED;// 对象向上转型
		System.out.println(msg.getMessage());

	}
}

demo3在枚举类定义抽象方法---没什么用

enum Color {
	RED("红色"){
		@Override
		public String getMessage(){// 覆写抽象方法
			return "[RED]" + this;// this.toString() 可以简化写成 `this`
		}
	},
	GREEN("绿色"){
		@Override
		public String getMessage(){
			return "[GREEN]" + this;
		}
	},
	BLUE("蓝色"){
		@Override
		public String getMessage(){
			return "[BLUE]" + this;
		}
	};

	private String title;// 成员属性
	private Color(String title){
		this.title = title;
	}

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

	public abstract String getMessage();// 直接定义抽象方法
}

public class JavaDemo {
	public static void main(String args[]) {
		System.out.println(Color.RED.getMessage());
	}
}
posted @ 2023-07-01 16:02  盘思动  阅读(6)  评论(0编辑  收藏  举报