JAVA/in 기초

Java에서의 상수와 enum(열거형) 사용 예제 및 설명

lahuman 2014. 2. 23. 23:41
728x90

기본적으로 자바에서 상수를 만드느 방법은 final 키워드를 이용하거나 인터페이스를 이용 하는 방법이 있다.

* 상수의 의미는 단 한번 초기화를 거칠 수 있으며 절대 변경이 불가능 한 것을 이야기한다.


클래스에서 상수 선언

 - final 키워드를 이용하여 상수로 선언한다.

 - 선언할때 단 한번 초기화를 한다.

 - static final로 선언하면 전역적인 상수가 된다.

* 보통의 경우 static final로 선언하여 전역적인 상수를 만들어 사용한다.


클래스를 이용한 상수 선언

public class Constants4Class {
    private Constants4Class(){};
    public static final double PI = 3.14;
}

인터페이스를 이용한 상수 선언
 - 인터페이스 맴버 변수는 상수만 설정 가능하다.
 - 일반 맴버 변수를 선언하더라도 static final 이된다.

public interface Constants4Interface {
    double PI = 3.14;
}


사용예제

public class Runner {
    public static void main(String[] args){
        System.out.println(Constants4Class.PI);
        System.out.println(Constants4Interface.PI);
    }
}


java 5.0 부터는 enum이라는 데이터 타입을 가진 열거형 클래스을 제공한다.

기본 사용법

public enum EnumSample1 {
    BLACK, YELLOW, GREEN, BLUE, RED
}

실행 방법

for(EnumSample1 f : EnumSample1.values()){
    System.out.println(f + ":" + f.name() + ":" + f.ordinal());
}

열거형을 사용하는 가장 큰 이유는 숫자 상수를 이용하는 것보다 열거형 상수를 사용하는 것이 훨씬 직관적이기 때문이다. 게다가 열거형에서는 상수들을 묶어서 관리 할 수 있다는 장점도 있다


다음은 enum의 고급 활용 법이다.


1. 클래스 내부에 끼어 넣을 수 있다.

public class EnumSample2 {
    public enum Color {
        WHITE, BLACK, RED, YELLOW, BLUE
    }
}


2. overrides toString() method

public enum EnumSample3 {
    WHITE, BLACK, RED, YELLOW, BLUE;  //; is required here.

    @Override
    public String toString() {
        //only capitalize the first letter
        String s = super.toString();
        return s.substring(0, 1) + s.substring(1).toLowerCase();
    }
}


3. 사용자 정의 생성자를 추가 할수 있다.

public enum EnumSample4 {
    WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);
    private int code;
    private EnumSample4(int c) {
        code = c;
    }
    public int getCode() {
        return code;
    }
}


4. 인터페이스의 구현체가 될 수 있다.

public enum EnumSample5 implements Runnable{
    WHITE, BLACK, RED, YELLOW, BLUE;

    @Override
    public void run() {
        System.out.println("name()=" + name() +
                ", toString()=" + toString());
    }
}


5. 고급 예제 샘플

public enum EnumSample6 {
    PASSED(1, "Passed", "The test has passed."),
    FAILED(-1, "Failed", "The test was executed but failed."),
    DID_NOT_RUN(0, "Did not run", "The test did not start.");

    private int code;
    private String label;
    private String description;

    /**
     * A mapping between the integer code and its corresponding Status to facilitate lookup by code.
     */
    private static Map codeToStatusMapping;

    private EnumSample6(int code, String label, String description) {
        this.code = code;
        this.label = label;
        this.description = description;
    }

    public static EnumSample6 getStatus(int i) {
        if (codeToStatusMapping == null) {
            initMapping();
        }
        return codeToStatusMapping.get(i);
    }

    private static void initMapping() {
        codeToStatusMapping = new HashMap();
        for (EnumSample6 s : values()) {
            codeToStatusMapping.put(s.code, s);
        }
    }

    public int getCode() {
        return code;
    }

    public String getLabel() {
        return label;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Status");
        sb.append("{code=").append(code);
        sb.append(", label='").append(label).append('\'');
        sb.append(", description='").append(description).append('\'');
        sb.append('}');
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(EnumSample6.PASSED);
        System.out.println(EnumSample6.getStatus(-1));
    }
}


고급 활용법 출처 : http://javahowto.blogspot.kr/2008/04/java-enum-examples.html



728x90