관리 메뉴

나만의공간

JAVA enum 사용법 본문

IT/JAVA

JAVA enum 사용법

밥알이 2017. 3. 16. 19:58

자바 enum 사용법

자바 1.5부터 제공되는 enum에 대한 사용법

기본사용법

City.java

public enum City {
    SEOUL,
    NEWYORK,
    ATHENS,
    BERLIN,
    MOSCOW,
    SINGAPORE,
    ;
}

Sample.java

public class Sample {

    public static void main(String[] args) {
        System.out.println(City.NEWYORK);
    }
}

초기값 설정사용법

CityHangul.java

public enum CityHangul {
    SEOUL("서울"),
    NEWYORK("뉴욕"),
    ATHENS("아테네"),
    BERLIN("베를린"),
    MOSCOW("모스크바"),
    SINGAPORE("싱가폴"),
    ;

    private String cityName;

    CityHangul(String cityName) {
        this.cityName = cityName;
    }

    public String cityName() {
        return cityName;
    }
}

Sample.java

public class Sample {

    public static void main(String[] args) {
        System.out.println(CityHangul.SEOUL.cityName());
    }
}


enum에 로직 추가

BigDecimalCal.java

public enum BigDecimalCal {
    PLUS,
    MINUS,
    MULTIPLY,
    DIVIDE,
    ;

    BigDecimal operation(BigDecimal a, BigDecimal b) {
        switch (this) {
            case PLUS :
                return a.add(b);
            case MINUS :
                return a.subtract(b);
            case MULTIPLY :
                return a.multiply(b);
            case DIVIDE :
                return a.divide(b);
            default :
               throw new AssertionError("지원하지 않는 공식입니다");

        }
    }
}

Sample.java

public class Sample {

    public static void main(String[] args) {
        BigDecimal num1 = BigDecimalCal.PLUS.operation(new BigDecimal(100), new BigDecimal(20));
        System.out.println(num1);

        BigDecimal num2 = BigDecimalCal.MINUS.operation(new BigDecimal(100), new BigDecimal(20));
        System.out.println(num2);

        BigDecimal num3 = BigDecimalCal.MULTIPLY.operation(new BigDecimal(100), new BigDecimal(20));
        System.out.println(num3);

        BigDecimal num4 = BigDecimalCal.DIVIDE.operation(new BigDecimal(100), new BigDecimal(20));
        System.out.println(num4);
    }
}








Comments