Home > Java > JavaBase > What exactly are enumerations in java?

What exactly are enumerations in java?

(*-*)浩
Release: 2019-11-12 09:35:28
Original
3363 people have browsed it

An enumeration is a special data type. The reason why it is special is that it is a class type but has some more special constraints than a type. However, the existence of these constraints also creates an enumeration. Type simplicity, safety, and convenience.

What exactly are enumerations in java?

To create an enumeration type, you must use the enum keyword, which implies that the types created are all java.lang. A subclass of the Enum class (java.lang.Enum is an abstract class).

The enumeration type conforms to the general pattern Class Enum>, and E represents the name of the enumeration type. (Recommended learning: java course)

Each value of the enumeration type is mapped to the protected Enum(String name, int ordinal) constructor, where the name of each value are converted to a string, and the ordinal setting represents the order in which this setting is created.

Use of enumeration:

Create an enumeration class: EnumTest

public enum EnumTest {
	//星期一,星期二,星期三,星期四,星期五,星期六
	MON(1), TUE(2),WED(3),THU(4),FRI(5),SAT(6){	
		public boolean isRest(){
			return true;
		}
	},
	//星期日
	SUN(0){
		public boolean isRest(){
			return true;
		}
	};
	private int value;
	private  EnumTest(int value){
		this.value=value;
	}
	public int getValue(){
		return value;
	}
	public boolean isRest(){
		return  false;
	}
}
Copy after login

Use EnumTest enumeration class:

public class EnumMain {
	public static void main(String[] args) {
		for (EnumTest enumTest : EnumTest.values()) {
			System.out.println(enumTest + ":" + enumTest.getValue());
		}
		System.out.println("---------------我是分割线------------");
		EnumTest test = EnumTest.SAT;
		switch (test) {
		case MON:
			System.out.println("今天是星期一");
			break;
		case TUE:
			System.out.println("今天是星期二");
			break;
		case WED:
			System.out.println("今天是星期三");
			break;
		case THU:
			System.out.println("今天是星期四");
			break;
		case FRI:
			System.out.println("今天是星期五");
			break;
		case SAT:
			System.out.println("今天是星期六");
			break;
		case SUN:
			System.out.println("今天是星期日");
			break;
		default:
			System.out.println(test);
			break;
		}
	}
}
Copy after login

The above is the detailed content of What exactly are enumerations in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template