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.

  • 相关阅读:
    我已经发表的文章:2,《上帝的小蚂蚁》(未经作者本人同意,不得转载!)
    【windows环境下】RabbitMq的安装和监控插件安装
    Apache FtpServer扩展【动手实现自己的业务】
    我的博客开始之旅
    curl和wget的区别和使用 wanglf
    ceph集群部署 wanglf
    ansible实现SSH配置免密互信 wanglf
    kubernetes(k8s) helm安装kafka、zookeeper wanglf
    django项目中使用KindEditor富文本编辑器 wanglf
    下一代网页:当HTML5取代Flash
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3153345.html
Copyright © 2011-2022 走看看