Java 枚举类简单使用

1 简单的枚举类

// 创建一个枚举类
package com.lihaogn.test;
public enum SeasonEnum {
	
	// 定义四个枚举实例
	SPRING,SUMMER,AUTUMN,WINTER;

}

// 测试类
package com.lihaogn.test;
public class Test {
	public static void main(String[] args) {
		for (SeasonEnum s : SeasonEnum.values()) {
			System.out.println(s);
		}
	}
}

// result
SPRING
SUMMER
AUTUMN
WINTER

2 进阶使用

// 创建一个枚举类
package com.lihaogn.test;
public enum SeasonEnum {
	// 定义四个枚举实例
	SPRING(1,"春"),SUMMER(2,"夏"),AUTUMN(3,"秋"),WINTER(4,"冬");
    
	private final int id;
	private final String name;

	private SeasonEnum(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public String getName() {
		return name;
	}
}

// 测试类
package com.lihaogn.test;
public class Test {
	public static void main(String[] args) {

		for (SeasonEnum s : SeasonEnum.values()) {
			System.out.println(s);
		
		}
		
		System.out.println(SeasonEnum.SPRING.getId());
		System.out.println(SeasonEnum.SPRING.getName());
	}
}

// result
SPRING
SUMMER
AUTUMN
WINTER
1

你可能感兴趣的:(01,Java,学习)