Java Programming Introductory Tutorial--The Role of Enumeration Classes

Declare enum type format

       In some cases, the objects of a class are limited and fixed, such as the direction class, which only has 4 objects, and any other value is illegal. At this time, you can consider using an enumeration class.

     An enumeration type is a data type of a constant collection, and the format for declaring an enumeration type is as follows:

   [public] enum enumeration type name { enumeration member 1 , enumeration member 2 , ... enumeration member n ; }

       The enumeration members are separated by commas, and each member represents a unique value. A variable of the enumeration type can only be assigned one of the declared constant values.

Note: A source file can only define one enumeration type of public type. After the enumeration class is compiled by the Java compiler, a bytecode file (.class) will also be generated. An enumeration type is essentially a class, but a special one.

sample program

package test;

enum Directions{
	EAST, SOUTH, WEST, NORHT;
}

public class JavaDemo {
	public static void main(String[] args) {
		Directions dir = Directions.EAST;
		System.out.println(dir);
	}
}

The program running result is shown in the figure.


An object of enumeration type can only be assigned one of the declared constant values, and
the format of the assignment is:
enumeration class name object name = enumeration class.constant value

 

Guess you like

Origin blog.csdn.net/u010764893/article/details/131123948