Today, I want to write a simple example:
This is the content of the myenum. Java file:
/*
* To change this template, choose tools | templates
* And open the template in the editor.
*/
Package myenum;
/**
*
* @ Author long
*/
// Define enumeration class
Public Enum myenum
{
Login ("login"), register ("register"), logout ("logout"), onlinecheck ("checkonlie ");
Private string name;
Private myenum (string name)
{
This. Name = Name;
}
}
// Or you can write this class as follows:
// Public Enum myenum
//{
// Login, register, logout, onlinecheck;
//}
========================================================== ==============
This is the content of the Main. Java file:
/*
* To change this template, choose tools | templates
* And open the template in the editor.
*/
Package myenum;
/**
*
* @ Author long
*/
Public class main {
/**
* @ Param ARGs the command line arguments
*/
Public static void main (string [] ARGs ){
// Todo code application logic here
// The combination of enumeration classes and switch statements
// Myenum operate = myenum. valueof ("login ");
Myenum operate = myenum. login;
Switch (operate)
{
Case login:
System. Out. println ("this is login ");
Break;
Case Register:
System. Out. println ("this is register ");
Break;
Case logout:
System. Out. println ("this is logout ");
Break;
Case onlinecheck:
System. Out. println ("this is onlinecheck ");
Break;
Default:
System. Out. println ("there is no Enum value! ");
Break;
}
// The values obtained by the two methods are the same.
System. Out. println (myenum. Register. tostring ());
System. Out. println (myenum. valueof ("logout "));
}
}
==================
Note the following when using enumeration classes:
1. The list of enumerated elements must be written at the beginning of the enumeration class. Each element is separated by a comma. If there is no other content after the end of the element list, you can leave it a semicolon. Otherwise, you must write it.
2. All constructors in the enumeration class are private. External programs cannot create enumeration class instances. In the enumeration class, you can explicitly specify which builder to call, such as member and member (). The list declarations are equivalent and both call the default builder, member ("common member") explicitly specifies that the program calls the second builder.
3. Enumeration classes can have abstract methods, but these methods must be implemented in the element list declaration. In addition, some common member variables and methods can be declared in the enumeration class, as shown in the preceding example.