"Simple Java" Java enumeration example

Source: Internet
Author: User

Enumerations in Java are similar to other ordinary classes in that they contain a set of pre-defined objects in their own right.

Here are a few examples of enumerations that can help us better use enumeration types;

A simple example
 Package Simplejava; enum Color {    // Each is a instance of Color}publicclass  Q5 {      Public Static void Main (string[] args) {        for  (Color color:Color.values ()) {            System.out.println ( color);     }}}

Result output:

RED
YELLOW
Blue Call construction method
 PackageSimplejava;enumColor {RED (1), YELLOW (2), BLUE (3);//Each are an instance of Color    Private intvalue; PrivateColor (inti) { This. Value =i; }     Public voidPrintvalue () {System.out.println ( This. Value); }} Public classQ5 { Public Static voidMain (string[] args) { for(Color color:Color.values ()) {color.printvalue (); }    }}

Results Print:

1
2
3 When to use enumerations

The enumeration in Java is similar to the normal class, and contains a set of predefined objects in the interior.

A better use case is to block invalid parameters. The following code example:

 Public void dosomethingwithcolor (int color);

This is an ambiguous interface, and other developers simply do not know which parameters to pass to this interface, only the int type;

For example, if you have an enumeration type color that contains a collection of black,red two objects, then this interface becomes this:

 Public void dosomethingwithcolor (color color);

The use of enumeration types will greatly enhance the readability of your code while preventing the passing of invalid parameters;

Link: http://www.programcreek.com/2014/01/java-enum-examples/

"Simple Java" Java enumeration example

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.