[JAVA] enum

Coastby·2022년 9월 28일
0

JAVA

목록 보기
26/33

enum

interface에서 field를 만들면 public static final이 암시가 된다.

interface FRUIT {
	int APPLE=1, PEACH=2, BANANA=3;
}
.
.
int type = FRUIT.APPLE;

==

private final static int FRUIT_APPLE =  1;
private final static int FRUIT_PEACH =  2;
private final static int FRUIT_BANANA =  3;
.
.
int type = FRUIT_APPLE;

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

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(){}
}

==

enum Fruit{
    APPLE, PEACH, BANANA;
}
enum Fruit {
	APPLE("red"), PEACH("pink"), BANANA("yellow");
	private String color;
	public String getColor() {
		return this.color;
	}
	Fruit(String color) {
		this.color = color;
	}
}

public class ConstantDemo {

	public static void main(String[] args) {
		
		for(Fruit f : Fruit.values()) {
			System.out.println (f+", "+f.getColor());
		}
		
		Fruit type = Fruit.APPLE;
		switch (type) {
		case APPLE:
			System.out.println(57+"kcal, color "+ Fruit.APPLE.getColor());
			break;
		case PEACH:
			System.out.println(34+"kcal, color "+ Fruit.PEACH.getColor());
			break;
		case BANANA:
			System.out.println(93+"kcal, color "+ Fruit.BANANA.getColor());
			break;
		}

	}

}

어떤 상수들이 있는 지는 몰라도 배열처럼 꺼내서 쓸 수 열거를 할 수 있다.

profile
훈이야 화이팅

0개의 댓글