출처

열거형(enum) - 프로그래밍 입문

**enum은 열거형(enumerated type)**이라고 부른다. 열거형은 서로 연관된 상수들의 집합이라고 할 수 있다.

package org.opentutorials.javatutorials.constant2;

enum Fruit{
	APPLE, PEACH, BANANA;
}

enum Company{
	GOOGLE, APPLE, ORACLE;
}

public class ConstantDemo {
	public static void main(String[] args) {
		/*
		if(Fruit.APPLE == Company.APPLE){
			System.out.println("과일 애플과 회사 애플이 같다.");
		}
		*/

		Fruit type = Fruit.APPLE;
		switch(type){

			case APPLE:
				System.out.println(57+" kcal");
				break;

			case PEACH:			
				System.out.println(34+" kcal");
				break;
			
			case BANANA:
				System.out.println(93+" kcal");
				break;		
		}
	}
}

enum은 class, interface와 동급의 형식을 가지는 단위다. 하지만 enum은 사실상 class이다. 편의를 위해서 enum만을 위한 문법적 형식을 가지고 있기 때문에 구분하기 위해서 enum이라는 키워드를 사용하는 것이다. 위의 코드는 아래 코드와 사실상 같다.

class Fruit{
	public static final Fruit APPLE  = new Fruit();
	public static final Fruit PEACH  = new Fruit();
	public static final Fruit BANANA = new Fruit();
	**private** Fruit(){}
}

생성자의 접근 제어자가 private이다. 그것이 클래스 Fruit를 인스턴스로 만들 수 없다는 것을 의미한다. 다른 용도로 사용하는 것을 금지하고 있는 것이다.

아래 코드는 컴파일 에러가 발생한다.

if(Fruit.APPLE == Company.APPLE){
	System.out.println("과일 애플과 회사 애플이 같다.");
}

enum이 서로 다른 상수 그룹에 대한 비교를 컴파일 시점에서 차단할 수 있다는 것을 의미한다.

enum과 생성자

enum은 사실 클래스다. 그렇기 때문에 생성자를 가질 수 있다. 아래와 같이 코드를 수정해보자.

package org.opentutorials.javatutorials.constant2;

enum Fruit{
	APPLE, PEACH, BANANA;

	**Fruit(){
		System.out.println("Call Constructor "+this);
	}**
}

결과는 아래와 같다.

Call Constructor APPLE

Call Constructor PEACH

Call Constructor BANANA

57 kcal