enum 枚举类

发布时间:2024年01月23日
package com.ztt.Demo01;
//枚举
public class demo01 {

	public static void main(String[] args) {
		// 保存星期几
//		int dayOfWeek1=250;
//		String dayOfWeek2="伍佰";
		
		Week dayOfWeek1=Week.SUN;
		System.out.println(dayOfWeek1.toString());
		
	}

}
//枚举
enum Week{
	//当前枚举值
	MON("星期一"),TUE("星期二"),WED("星期三"),THR("星期四"),FRI("星期五"),SAT("星期六"),SUN("星期日");
	
	//成员变量
	private String value;
	
	//构造方法(必须私有)
	private Week(String value) {
		this.value=value;
	}
	
	//重写枚举类Enum的toString()
	@Override
	public String toString() {
		return this.value;
	}
}

//类
final class weekx {
	private String weekName;
	
	public static final weekx MON = new weekx("星期一");
	public static final weekx TUE = new weekx("星期二");
	public static final weekx WED = new weekx("星期三");
	public static final weekx THR = new weekx("星期四");
	public static final weekx FRI = new weekx("星期五");
	public static final weekx SAT = new weekx("星期六");
	public static final weekx SuN = new weekx("星期曰");
	
	//构造方法私有化
	private weekx ( String weekName) {
		this.weekName = weekName;
	}
	//重写0bject类toString()@override
	public String tostring() {
		return this.weekName;
	}
}

运行结果:

星期日
package com.ztt.Demo01;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;

public class demo02 {
	public static void main(String[] args) {
		//星期枚举类
		DayOfWeek dw1 = LocalDate.now().getDayOfWeek();
		DayOfWeek dw2=DayOfWeek.FRIDAY;
		//月份枚举类
		Month m1 = LocalDate.now().getMonth();
		Month m2 = Month.AUGUST;
		System.out. println( m2.toString());
		System.out.println("序号:"+ m2.ordinal());//序号
		System.out.println("月份:"+m2.getValue());
	}
}

运行结果:

AUGUST
序号:7
月份:8
package com.ztt.Demo01;

public class demo03 {
	public static void main(String[] args) {
		Color c1=Color.BLUE;
		System.out.println(c1);
	}
}

enum Color{
	RED(255,0,0),GREEN(0,255,0),BLUE(0,0,255);
	
	private int r;
	private int g;
	private int b;
	
	private Color(int r,int g,int b) {
		this.r=r;
		this.g=g;
		this.b=b;
	}
	@Override
	public String toString() {
		return String.format("RED[%d],GREEN[%d],BLUE[%d]", this.r,this.g,this.b);
	}
}

运行结果:

RED[0],GREEN[0],BLUE[255]

?

?

?

?

?

?

文章来源:https://blog.csdn.net/m0_68041576/article/details/135782272
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。