Skip to content

Java:Enumeration

Java의 열거형 (Enumeration)에 대한 설명.

About

Java enum class는 열거형(enumeration)타입으로, 개발에 필요한 열거형 상수들을 적절히 모을 수 있는 방법을 제공한다.

기본 형태

원소들간의 구분은 콤마(,)로 한다. 그리고 enum 객체 역시 클래스이기 때문에 기본생성자가 있어야한다. 물론, 생성자를 생략해도 Java가 디폴트 생성자를 만들어줍니다.

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

더 간단하게 인라인 클래스로 배열 선언하듯 사용할 수 있다.

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

추가 속성을 부여한 형태

아래와 같이 enum class의 생성자를 재정의하면 또다른 자료형을 부여할 수 있다.

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