10.11 定义枚举结构

发布时间 2023-07-01 16:07:10作者: 盘思动

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~~蓝色