Why use enums




















You can use enum types any time you need to represent a fixed set of constants. You can use enums when a variable especially a method parameter can only take one out of a small set of possible values. Examples would be things like days in a Week Sunday, Monday etc.. You can use an enum instead of a class if the class should have a fixed enumerable number of instances. You can also use an enum type in a Java switch You can use Enum in Java inside the Switch statement like int or char primitive data type.

The following program shows how to use Enum in switch You can also use an enum type in a Java if.. The following program shows how to use Enum in if.. The above method is not only ambiguous do day indexes start at 1, or at 0?

An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties. Whenever a procedure accepts a limited set of variables, consider using an enumeration. Enumerations make for clearer and more readable code, particularly when meaningful names are used.

Ensures forward compatibility. With enumerations, your code is less likely to fail if in the future someone changes the values corresponding to the member names.

Use a naming convention for enumeration members. When Visual Basic encounters an enumeration member name, an exception may be thrown if other referenced type libraries contain the same name. The enum declaration defines a class called an enum type. The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system. In the following example, Planet is an enum type that represents the planets in the solar system.

They are defined with constant mass and radius properties. Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods.

Also, when there are fields and methods, the list of enum constants must end with a semicolon.



0コメント

  • 1000 / 1000