枚举类


枚举类

枚举也属于类,它继承自Enum类

定义

使用关键字 enum

public enum Status{
	RUNNING,STUDY,SLEEP;
}

此时枚举类中的RUNNING,STUDY,SLEEP都是以 public static final Status 类型存放,相当于一个Status类的成员变量

因此,枚举类中还可以定义成员变量,定义有参构造方法等。需要注意的是,如果定义了有参构造方法,RUNNING等状态都要在后面用 ( )来进行参数绑定了,这是因为在Java中,枚举(enum)的构造方法是私有的,无法声明为publicprotected,枚举中,构造函数默认是private的,如果尝试将其声明为publicprotected,编译器会报错。因此,所有的枚举实例必须在枚举类内进行定义,不能在类外创建新的实例。

例如:

public enum Status{
	RUNNING("跑步"),STUDY("学习"),SLEEP("睡觉");
	
	private final String name;//枚举的成员变量
	Status(String name){      //覆盖原有无参构造方法,注意不能加public!!
			this.name=name;
		}
	
	public void getName(){
		return name;
	}
}

使用

当做一个数据类型定义使用

public class Student{
	private Status status;
	
	//Setter
	public void setStatus(String status){
		this.status=status;
	}
	
	//Getter
	public String getStatus(){
		return this.status;
	}
}

在枚举类的Setter函数中,用 枚举类名.内容 来进行值的更改:

public static void main(String[] args){
	Student student = new Student();
	student.setStatus(Status.RUNNING);
	System.out.println(student.getStatus());  //打印RUNNING
	System.out.println(student.getStatus().getName()); //打印跑步
	System.out.println(student.getStatus().name());    //打印RUNNING 
}

Author: havenochoice
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source havenochoice !
评论
  TOC