Java Arrays Tutorial (3)

Java Arrays Tutorial (3)

Data types have a specific set of values. A byte cannot hold a value larger than 127 and an int cannot hold a value larger than 2,147,483,647. You can also create your own data types that have a finite set of legal values. A programmer created data type with a fixed set of values is an enumerated data type.

In Java, you create an enumerated data type in a statement that uses the keyword enum, an identifier for the type, and a pair of curly braces that contain a list of the enum constants, which are the allowed values for the type. For example, the following code creates an enumerated type named Month that contains 12 values:

Enum Month{JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC};

After you create an enumerated data type, you can declare variables of that type. For example, you might declare the following:

Month birthMonth;

You can assign any of the enum constants to the variables. Therefore, you can code a statement such as the following:

birthMonth = Month.MAY;

An enumeration type like Month is a class, and its enum constants act like instantiated from the class, including having access to the methods of the class.

Creating an enumeration type provides you with several advantages:

(1). If you did not create an enumerated type for month values, you could use another type, for example, ints or Strings. The problem is that any value could be assigned to an int or String variable, but only the 12 allowed values can be assigned to a Month.

(2). If you did not create an enumerated type for month values, you could create another type to represent months, but invalid behavior could be applied to the values. For example, you could add or substract two months, which is not logical. Programmers say using enums makes the values type-safe. Type-safe describes a data type for which only appropriate behaviors are allowed.

(3). The enum constants provide a form of self-documentation. Someone reading your program might misinterpret what 9 means as a month value, but there is less confusion when you use the identifier OCT.

(3). As with other classes, you can also add methods and other fields to an enum type.

posted @ 2013-06-24 21:04  爱生活,爱编程  阅读(211)  评论(0编辑  收藏  举报