1. 열거형에 멤버 추가하기
- 불연속적인 열거형 상수의 경우, 원하는 값을 괄호()안에 적는다.
enum Direction { EAST(1), SOUTH(5), WEST(-1), NORTH(10) } // 여러개 가능 EAST(1, ">")
- 괄호()를 사용하려면, 인스턴스 변수와 생성자를 새로 추가해 줘야 한다.
enum Direction {
EAST(1), SOUTH(5), WEST(-1), NORTH(10); // 끝에 ';'를 추가해야 한다.
private final int value; // 정수를 저장할 필드(인스턴스 변수)를 추가
Direction(int value) { this.value = value; } // 생성자를 추가
public int getValue() { return value; }
}
- 열거형의 생성자는 묵시적으로 private이므로, 외부에서 객체생성 불가
Direction d = new Direction(1); // 에러. 열거형의 생성자는 외부에서 호출불가
2. 예제
enum Direction {
EAST(1, ">"), SOUTH(2, "V"), WEST(3, "<"), NORTH(4, "^");
private static final Direction[] DIR_ARR = Direction.values();
private final int value;
private final String symbol;
Direction(int value, String symbol) { // 접근제어자 private생략됨
this.value = value;
this.symbol = symbol;
}
public int getValue() { return value; }
public String getSymbol() { return symbol;}
public static Direction of(int dir) {
if(dir < 1 || dir > 4) // 1,2,3,4가 아니면 에러 던짐
throw new IllegalArgumentException("Invalid value : " + dir);
return DIR_ARR[dir -1];
}
// 방향을 회전시키는 메서드. num의 값만큼 90도씩 시계방향으로 회전한다.
public Direction rotate(int num) {
num = num % 4; // 0123
if(num < 0)
num += 4; // num이 음수일때 반대방향으로 회전
return DIR_ARR[(value-1+num) % 4];
}
public String toString() {
return name()+getSymbol();
}
}
public class Enum02_1 {
public static void main(String[] args) {
for (Direction d : Direction.values()) {
System.out.printf("%s=%d%n", d.name(), d.getValue());
Direction d1 = Direction.EAST;
Direction d2 = Direction.of(1);
System.out.printf("d1=%s, %d%n", d1.name(), d1.getValue());
System.out.printf("d2=%s, %d%n", d2.name(), d2.getValue());
System.out.println(Direction.EAST.rotate(1));
System.out.println(Direction.EAST.rotate(2));
System.out.println(Direction.EAST.rotate(-1));
System.out.println(Direction.EAST.rotate(-2));
}
}
}
'Java' 카테고리의 다른 글
124. 메타애너테이션 - 패스트캠퍼스 백엔드 부트캠프 3기 (2) | 2025.01.06 |
---|---|
123. 애너테이션 - 패스트캠퍼스 백엔드 부트캠프 3기 (2) | 2025.01.06 |
121. 열거형 - 패스트캠퍼스 백엔드 부트캠프 3기 (2) | 2025.01.03 |
120. 지네릭형변환 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.03 |
119. 와일드카드, 지네릭 메서드 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.03 |