Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

열거형에 멤버 추가하기 본문

Java/JAVA3

열거형에 멤버 추가하기

빌드이너프 2023. 7. 31. 10:34

열거형에 멤버 추가하기

불연속적인 열거형 상수의 경우, 원하는 값을 괄호()안에 적는다

enum Direction { EAST(1), SOUTH(5), WEST(-1), NORTH(10) }

 

괄호()를 사용하려면, 인스턴스 변수와 생성자를 새로 추가해 줘야한다

enum Direction {
    EAST(1), SOUTH(5), WEST(-1), NORTH(10); // 끝에 ';'를 추가
    
    private final int value; // 정수를 저장할 필드(인스턴스 변수)를 추가
    Direction(int value) { this.value = value; } // 생성자를 추가, 생성자 앞에 항상 private 생략되어 있다
    // private Direction(int value) { this.value = value; }
    
    public int getValue() { return value; }
}

 

열거형의 생성자는 묵시적으로 private이므로, 외부에서 객체생성 불가

Direction d = new Direction(1); // 에러, 열거형의 생성자는 외부에서 호출불가

 

코드

enum Direction2 {
    EAST(1, ">"), SOUTH(2,"V"), WEST(3, "<"), NORTH(4,"^");

    private static final Direction2[] DIR_ARR = Direction2.values();
    private final int value;
    private final String symbol;

    Direction2(int value, String symbol) { // 생성자 호출, 접근 제어자 private이 생략됨
        this.value  = value;
        this.symbol = symbol;
    }

    public int getValue()     { return value;  }
    public String getSymbol() { return symbol; }

    public static Direction2 of(int dir) {
        if (dir < 1 || dir > 4)
            throw new IllegalArgumentException("Invalid value :" + dir);

        return DIR_ARR[dir - 1];
    }

    // 방향을 회전시키는 메서드. num의 값만큼 90도씩 시계방향으로 회전한다.
    public Direction2 rotate(int num) {
        num = num % 4;

        if(num < 0) num +=4; // num이 음수일 때는 시계반대 방향으로 회전

        return DIR_ARR[(value-1+num) % 4];
    }

    public String toString() {
        return name()+getSymbol();
    }
} // enum Direction2

class enumTest {
    public static void main(String[] args) {
        for(Direction2 d : Direction2.values())
            System.out.printf("%s=%d%n", d.name(), d.getValue());

        Direction2 d1 = Direction2.EAST;
        Direction2 d2 = Direction2.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(Direction2.EAST.rotate(1));
        System.out.println(Direction2.EAST.rotate(2));
        System.out.println(Direction2.EAST.rotate(-1));
        System.out.println(Direction2.EAST.rotate(-2));
    }
}


EAST=1
SOUTH=2
WEST=3
NORTH=4
d1=EAST, 1
d2=EAST, 1
SOUTHV
WEST<
NORTH^
WEST<

'Java > JAVA3' 카테고리의 다른 글

메타 애너테이션  (0) 2023.08.01
Annotation(애너테이션) @  (0) 2023.07.31
열거형(enum)  (0) 2023.07.30
지네릭 형변환  (0) 2023.07.29
지네릭 메서드  (0) 2023.07.28