1. Enum

enum Direction {
    EAST(1),
	SOUTH(2),
	WEST(3),
	NORTH(4);

	private final int value;
	private Direction(int value) { this.value = value }
}


TO

1. Class

class Direction {
    static final Direction EAST = new Direction(“EAST”);
	static final Direction SOUTH = new Direction(“SOUTH”);
	static final Direction WEST = new Direction(“WEST”);
	static final Direction NORTH = new Direction(“NORTH”);

	private final String name;

	private Direction(String name) {
		this.name = name;
	}
}

2. Extends Enum

class MyEnum<? extends MyEnum<T>> implements Comparable<T> {
    static in id = 0;

	int ordinal;
	String name = “”;

	public int ordinal() { return ordinal; }

	MyEnum(String name) {
		this.name = name;
		ordinal = id++;
	}

	public int compareTo(T t) {
		// t.ordinal()은 MyEnum<? extends MyEnum<T>> 때문에 에러 없이 사용가능하다.
		// MyEnum<T> 였다면 T에 ordinal()이 있는지 확인이 되지 않아 에러가 발생했을 것이다.
		return ordinal - t.ordinal();
	}
}

3. Enum Abstract Method

3.1 Enum EX)

enum Direction {
    EAST(1) {
        Point move(Point p) { … }
    },
    SOUTH(2) {
        Point move(Point p) { … }
	},
    WEST(3) {
        Point move(Point p) { … }
    },
    NORTH(4) {
        Point move(Point p) { … }
    };
	
    // protected인 이유는 추상 메서드를 구현하는 상수에서 접근 하기 위함이다.
    protected final int value;
	
    Direction(int value) { this.value = value }
	
    abstract Point move(Point p);
}

3.2 Class EX)

abstract class Direction extends MyEnum {
    // 추상 클래스인 Direction을 생성하였기에 익명 클래스 형태로 추상 메서드인 move구현
    static final Direction EAST = new Direction(“EAST”) {
        Point move(Point p) { … }
    }

    // 추상 클래스인 Direction을 생성하였기에 익명 클래스 형태로 추상 메서드인 move구현
    static final Direction SOUTH = new Direction(“SOUTH”) {
        Point move(Point p) { … }
    }

    // 추상 클래스인 Direction을 생성하였기에 익명 클래스 형태로 추상 메서드인 move구현
    static final Direction WEST = new Direction(“WEST”) {
        Point move(Point p) { … }
    }

    // 추상 클래스인 Direction을 생성하였기에 익명 클래스 형태로 추상 메서드인 move구현
    static final Direction NORTH = new Direction(“NORTH”) {
        Point move(Point p) { … }
    }

    private String name;
    private Direction(String name) { this.name = name }

    // Direction의 추상 메서드 move 선언
    abstract Point move(Point p);
}

'개발 언어 > Java' 카테고리의 다른 글

[Java] Double Underscore  (0) 2021.10.22
[Java] 예외 처리  (0) 2021.08.27
[Java] 내부 클래스  (0) 2021.08.27
[Java] 인터페이스  (0) 2021.08.27
[Java] 추상 클래스&추상 메서드  (0) 2021.08.26

+ Recent posts