Skip to content
Search

Java:Enumeration

lastmod 2020-10-12created 2020-10-121 edits

An explanation of enumerations (Enumeration) in Java.

About

A Java enum class is an enumeration type that provides a way to properly group the enumeration constants needed for development.

Basic form

Elements are separated by commas (,). And since an enum object is also a class, it must have a default constructor. Of course, if you omit the constructor, Java creates a default constructor for you.

public enum FontStyle {
    NORMAL, BOLD, ITALIC, UNDERLINE;
    FontStyle() { }
}

More simply, you can use it as an inline class, like declaring an array.

public class SampleClass {
    public enum FontStyle { NORMAL, BOLD, ITALIC, UNDERLINE }
}

Form with additional properties

By overriding the constructor of the enum class as below, you can assign another data type.

public enum FontStyle {
    NORMAL("This font has normal style."),
    BOLD("This font has bold style."),
    ITALIC("This font has italic style."),
    UNDERLINE("This font has underline style.");

    private String description;

    FontStyle(String description) {
        this.description = description;
    }
    public String getDescription() {
        return this.description;
    }
}

See also

Favorite site

author Zer0 sitemap