📦 Enum

An enum type is a special data type that enables for a variable to be a set of predefined constants.
enum type은 미리 정의된 상수의 집합이 될 수 있도록 하는 특별한 데이터 타입이다.

The variable must be equal to one of the values that have been predefined for it.
변수는 미리 정의된 값 중 하나와 같아야 합니다.

Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
일반적인 예로는 나침반 방향(NORTH, SOUTH, EAST 및 WEST 값)과 요일이 포함됩니다.

 

방향 대신 Day로 예시를 들어보면 다음과 같다.

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}
Day.SUNDAY // SUNDAY

 

 

enum은 열거체를 비교할 때 실제 값뿐만 아니라 타입까지도 체크한다.

enum의 상숫값이 재정의되더라도 다시 컴파일할 필요가 없다.

 

enum Color {
    RED(3),
    YELLOW(4),
    BLUE(5);
    
    private final int value;
    Color(int value) { this.value = value; }
    public int getValue() { return value; }
}

 

System.out.println(Color.RED.name());      // RED
System.out.println(Color.RED.value());      // 3

 

1. 자바에서 상수 정의하기:: static final 

상수를 정의하는 방법에는 enum이 나타나기 전에 static final을 사용하는 방법이 있었다.

static final을 사용하는 방법 예시는 다음과 같다.

 

예시 상황으로 사용자는 1에서 100사이의 값만 입력할 수 있는 프로그램이 있다고 하자.
여기서 1과 100을 상수로 선언할 것이다. static final을 활용한 코드는 아래와 같다.

 

public class Application {
    private static final int MIN_SIZE = 1;
    private static final int MAX_SIZE = 100;
    
     public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int userInput = parseInt(in.readLine());
        if(userInput >= MIN_SIZE
                && userInput <= MAX_SIZE) {
            System.out.println("good");
        }
    }
}

 

 

이러한 static final 이 존재하였는데 왜 enum 이라는 열거형이 나왔을까?

 

Why created the enum?

  1. final static으로 상수를 선언하는 경우 상수 이름과 상수 값 자체는 관련이 없게된다.
  2. 이름의 충돌이 발생할 수 있다.

다음 예시를 통해 배경을 더 정확히 이해해보자!

 

final static으로 상수를 선언하는 경우 상수 이름과 상수 값 자체는 관련이 없게된다.

public class Application {
    private static final String SPRING = "봄";
    private static final String SUMMER = "여름";
    private static final String AUTUMN = "가을";
    private static final String WINTER = "겨을";
    
    public static void main(String[] args) {
    	System.out.println(SPRING); // 봄
        System.out.println(SUMMER); // 여름
        System.out.println(AUTUMN); // 가을
        System.out.println(WINTER); // 겨울
        
        String season = "봄";
        
        if (season == SPRING) {
        	System.out.printf("season is %s", SPRING); // season is 봄
        }
    }
}

 

 

이름의 충돌이 발생할 수 있다.

public class Framework {
    public static final int SPRING = 1;
    public static final int VUE = 2;
    public static final int NESTJS = 3;
}

public class Season {	
    public static final int SPRING = 1;
    public static final int SUMMER = 2;
    public static final int AUTUMN = 3;
    public static final int WINTER = 4;
}

// Season.SPRING Framework.SPRING 충돌

 

 

Advantages of using Enum instead of static final

  1. 코드가 단순해지고, 가독성이 좋아진다.
  2. 인스턴스 생성과 상속을 방지한다.
  3. enum 키워드 사용을 통해서 구현 의도가 열거형임을 분명하게 나타낼 수 있다.

 

static final 사용

private static final String SPRING = "봄";
private static final String SUMMER = "여름";
private static final String AUTUMN = "가을";
private static final String WINTER = "겨을";

 

 

enum 사용

public enum Season {
    SPRING("봄"),
    SUMMER("여름"),
    AUTUMN("가을"),
    WINTER("겨울");
    
    private final String value;
    Seson(String value) { this.value = value; }
    
    public String getValue() {
    	return value;
	}
}

 

final static 을 사용하여 선언한 상수보다 enum 을 사용한 상수 선언이 가독성 면에서 더 좋다.

 

 

 

 

 

 

Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects)

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated

docs.oracle.com

 

 

11주차 과제: Enum

11주차 과제: Enum · Issue #11 · whiteship/live-study 목표 자바의 열거형에 대해 학습하세요. 학습할 것 (필수) enum 정의하는 방법 enum이 제공하는 메소드 (values()와 valueOf()) java.lang.Enum EnumSet 마감일시 2021

hyeonic.tistory.com

 

 

[Java] 자바의 상수(Constant), final 변수 정리

상수(Constant) 프로그래밍 언어에서 상수는 변하지 말아야 할 데이터를 임시적으로 저장하기 위한 수단으로 사용된다. 즉, 초기화 이후 재할당이 불가능하다는 뜻이다. final 자바에서는 상수를 구

ittrue.tistory.com

 

 

Java: enum의 뿌리를 찾아서...

이번 글에서는 자바 1.5버전부터 새롭게 추가된 열거형 상수인 enum(enumeration)에 대해 알아보겠습니다. 열거형은 서로 연관된 상수들의 집합입니다. 이번 글은 enum 정의와 enum 사용방법, 그리고 enum

www.nextree.co.kr

 

 

Java Enum 활용기 | 우아한형제들 기술블로그

{{item.name}} 안녕하세요? 우아한 형제들에서 결제/정산 시스템을 개발하고 있는 이동욱입니다. 이번 사내 블로그 포스팅 주제로 저는 Java Enum 활용 경험을 선택하였습니다. 이전에 개인 블로그에 E

techblog.woowahan.com

 

728x90

'Language > JAVA' 카테고리의 다른 글

[JAVA] Vector Class  (1) 2023.11.29
[JAVA] Getter/Setter  (0) 2023.11.02
[JAVA] 생성자  (0) 2023.10.25
[JAVA] 값 복사와 주소 복사  (0) 2023.10.25
[JAVA] Java Collections / Array / ArrayList  (2) 2023.10.25

+ Recent posts