📦 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?
- final static으로 상수를 선언하는 경우 상수 이름과 상수 값 자체는 관련이 없게된다.
- 이름의 충돌이 발생할 수 있다.
다음 예시를 통해 배경을 더 정확히 이해해보자!
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
- 코드가 단순해지고, 가독성이 좋아진다.
- 인스턴스 생성과 상속을 방지한다.
- 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 을 사용한 상수 선언이 가독성 면에서 더 좋다.
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 |