티스토리 뷰

JAVA

enum in Java

seoca 2019. 6. 24. 05:46



enum 열거형


- enum은 연관된 상수들의 집합(a set of named constants.)으로 열거 순서에 따라 index번호를 부여받는다. 

- enum은 private constructor가 default이기에 public생성자의 생성이 금지된다 인스턴스를 만들 수 없다는 것은 즉, 다른 용도의 사용을 금한다는 의미이다. 

 




Example Code


enum Fruit{
APPLE, PEACH, BANANA;
Fruit(){
System.out.println("Constructor");
}
}

public class Main {

public static void main(String[] args) {
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;
}
}
}

//output
//Constructor
//Constructor
//Constructor
//57 kcal




위의 enum 클래스는 아래와 같은 의미이다. 결국 enum이나 interface나 인스턴스 생성은 불가능하며 public static final 로 다른 곳에서 변수를 자유롭게 사용한다 단, 수정은 불가

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






Reference

https://opentutorials.org/course/1223/6091

https://www.youtube.com/watch?v=sI4utYmh7O4