주로 몇 가지로 한정된 변하지 않는 데이터를 다루는데 사용
public static final int SPRING = 1;
public static final int SUMMER = 2;
public static final int FALL = 3;
public static final int WINTER = 4;
public static final int DJANGO = 1;
public static final int SPRING = 2; // 계절의 SPRING과 중복 발생!
public static final int NEST = 3;
public static final int EXPRESS = 4;
상수의 이름이 중복되어 컴파일에러 발생! 하지만,인터페이스로 해결은 가능하다
interface Seasons{
int SPRING = 1, SUMMER = 2, FALL = 3, WINTER = 4;
}
interface Frameworks {
int DJANGO = 1, SPRING = 2, NEST = 3, EXPRESS = 4;
}
위의 코드에서 Seasons.SPRING의 정수값 1과 Frameworks.SPRING의 정수값 2는 상수를 열거하기 위해 임의로 주어진 값이고, 그 외에 어떤 의미가 있는 값이 아님에도 아래와 같이 비교하는 코드를 작성할 수가 있다.
if (Seasons.SPRING == Frameworks.SPRING) {...생략...}
class Seasons {
public static final Seasons SPRING = new Seasons();
public static final Seasons SUMMER = new Seasons();
public static final Seasons FALL = new Seasons();
public static final Seasons WINTER = new Seasons();
}
class Frameworks {
public static final Frameworks DJANGO = new Frameworks();
public static final Frameworks SPRING = new Frameworks();
public static final Frameworks NEST = new Frameworks();
public static final Frameworks EXPRESS = new Frameworks();
}
근데 매번 이렇게 쓰자니 너무 복잡하다
enum Seasons { SPRING, SUMMER, FALL, WINTER }
enum Frameworks { DJANGO, SPRING, NEST, EXPRESS }
enum Seasons { SPRING, SUMMER, FALL, WINTER }
public class EnumTest {
public static void main(String[] args) {
Seasons[] sea = Seasons.values();
for(Seasons x: sea) {
System.out.printf("%s=%d%n", x.name(), x.ordinal());
}
Seasons xx = Seasons.valueOf("SPRING");
System.out.println(xx);
}
}
//출력값
SPRING=0
SUMMER=1
FALL=2
WINTER=3
SPRING
좋은 글이네요. 공유해주셔서 감사합니다.