Home >Java >javaTutorial >Introduction and use of enumerations

Introduction and use of enumerations

零下一度
零下一度Original
2017-07-20 13:34:012076browse

1.What is an enumeration?

An enumeration in C/C++/c#, as well as Objective-C, is a collection of named integer constants , enumerations are common in daily life. For example, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY representing the day of the week is an enumeration. The description of enumerations is similar to structures and unions.

2. Construction method

# The construction method of the enumeration type must be a private type to prevent instances outside the limited scope Enumeration object.

3. Custom methods

Methods can be defined in enumeration types, which are shared by all enumeration members.

4. Type safety

The enumeration type provides a parameter type detection mechanism. If the formal parameter of a method is defined as an enumeration Enumeration type, the actual parameter passed in when calling this method is not an enumeration member, and the compilation cannot pass.

5. Usage occasions

If a variable has a limited value range and can be listed one by one, then these values ​​can be defined as enumerations cite type members. Usually this variable is used as a formal parameter of a method. If the parameter passed in when calling the method is not a member of the specified enumeration type, compilation will not pass. In summary, enumerations are generally used in situations where the values ​​are fixed and limited.
Since enumerations can define methods, this enriches the behavior of enumeration members.

6. Common methods

  • EnumClass.values(): Returns enumeration type members in array form, mainly Used to traverse enumeration type members.

  • EnumConstant.name(): Returns the name of the enumeration type member, which is the variable name when declared.

The above is the detailed content of Introduction and use of enumerations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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