How do I create enumerations type?

Category: fundamental, viewed: 1024 time(s).

Enumeration is a list of named constants. Every most commonly used programming languages support this feature. But in Java it is officially supported since version 5.0. In Java programming language an enumeration defines a class type. Because an enumeration is a class it can have a constructors, methods, and instance variables.

To create an enumeration we use the enum keyword. For example below is a simple enumeration that hold a list of notebook producers:

package org.kodejava.example.fundametal;

public enum Producer {
    ACER, APPLE, DELL, FUJITSU, LENOVO, TOSHIBA;
}

//
// Below we use our enumeration in a simple program.
//
package org.kodejava.example.fundametal;

public class EnumDeclaration {
    public static void main(String[] args) {
        //
        // Creating an enum variable declaration and assignment. Because the
        // produced is of type Producer we can only assign value defined by
        // enumeration.
        //
        Producer producer = Producer.APPLE;
        
        if (producer == Producer.LENOVO) {
            System.out.println("Produced by Lenovo.");
        } else {
            System.out.println("Produced by others.");
        }
    }
}

The ACER, APPLE, DELL, etc identifiers are called enumeration constants. Every named constants have an implicitly assigned public and static access modifiers. Once we have defined the enumeration we can create a variable of that type. Although the enumeration is a class type to create an enumeration variable we don't use the new keyword. We create an enum just like creating a primitive type of data, as you can see in the example above.

Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats