zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    阶乘
    资金账号,手机号等中间添加*(星号),脱敏
    对象深拷贝
    前端简易服务器
    Codeforces Round #603 (Div. 2) C. Everyone is a Winner! (数学)
    Codeforces Round #603 (Div. 2) B. PIN Codes
    Codeforces Round #603 (Div. 2) A. Sweet Problem(数学)
    Codeforces Round #605 (Div. 3) E. Nearest Opposite Parity(最短路)
    Codeforces Round #605 (Div. 3) D. Remove One Element(DP)
    Codeforces Round #605 (Div. 3) C. Yet Another Broken Keyboard
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3153345.html
Copyright © 2011-2022 走看看