Enum은 열거형 데이터 타입으로, 한정된 고정된 값들의 집합을 정의할 때 사용된다.
Enum 클래스는 상수 집합을 정의하며, 각 값은 Enum의 인스턴스로 간주된다
특징
1. Enum은 클래스처럼 동작하며, 고유 메서드와 필드를 가질 수 있다.
2. 상수 값은 컴파일 시점에 결정되며 변경 불가능(불변)하다.
3. 코드 가독성을 높이고, 상수 값의 오타나 잘못된 값을 방지한다.
4. enum은 기본적으로 java.lang.Enum 클래스를 상속받는다.
사용법 1
// Enum 정의
public enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
// Enum 값을 참조
Day today = Day.MONDAY;
System.out.println("Today is: " + today); // 출력: Today is: MONDAY
// Enum의 모든 값 출력
for (Day day : Day.values()) {
System.out.println(day);
}
// 출력:
// MONDAY
// TUESDAY
// ...
// SUNDAY
// Enum 값 비교
if (today == Day.MONDAY) {
System.out.println("Start of the work week!");
}
// Enum 값 순서 확인
System.out.println(Day.MONDAY.ordinal()); // 출력: 0
System.out.println(Day.WEDNESDAY.ordinal()); // 출력: 2
설명
사용법 2
Enum은 상수 외에도 필드와 메서드를 가질 수 있다.
public enum Season {
SPRING("Flowers bloom"),
SUMMER("Hot and sunny"),
FALL("Leaves fall"),
WINTER("Cold and snowy");
private final String description;
// 생성자
Season(String description) {
this.description = description;
}
// 필드 반환 메서드
public String getDescription() {
return description;
}
}
Season currentSeason = Season.FALL;
System.out.println("Season: " + currentSeason);
System.out.println("Description: " + currentSeason.getDescription());
// 출력:
// Season: FALL
// Description: Leaves fall
Enum의 switch문 사용
Enum은 switch 문에서 자연스럽게 사용할 수 있다.
public class Main {
public static void main(String[] args) {
Day today = Day.SATURDAY;
switch (today) {
case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY:
System.out.println("It's a weekday!");
break;
case SATURDAY, SUNDAY:
System.out.println("It's the weekend!");
break;
}
}
}
// 출력: It's the weekend!
Enum 클래스를 활용한 복잡한 로직 구현
ex 커맨드 패턴
public enum Operation {
ADD {
@Override
public int apply(int x, int y) {
return x + y;
}
},
SUBTRACT {
@Override
public int apply(int x, int y) {
return x - y;
}
},
MULTIPLY {
@Override
public int apply(int x, int y) {
return x * y;
}
},
DIVIDE {
@Override
public int apply(int x, int y) {
return x / y;
}
};
// 추상 메서드 정의
public abstract int apply(int x, int y);
}
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 5;
for (Operation op : Operation.values()) {
System.out.printf("%s of %d and %d is %d%n", op, x, y, op.apply(x, y));
}
}
}
// 출력:
// ADD of 10 and 5 is 15
// SUBTRACT of 10 and 5 is 5
// MULTIPLY of 10 and 5 is 50
// DIVIDE of 10 and 5 is 2