enum class
//값이 필요 없는 경우
public enum OverTimeValues { A, B, C; }
//값을 할당하여 사용하는 경우, 최초 사용 시, 각 enum value마다 한번씩 생성자가 호출된다.
//이후 호출 시에는 생성자가 호출되지 않음.
public enum OverTimeValues { A(1000), B(2000), C(3000); private final int am; OverTimeValues(int am) { System.out.println("Ctor called : "+ am); this.am=am; } public int getAmount() { return am; } } public static void main(String [] args) { TestApplication test = new TestApplication(); enumTest(OverTimeValues.A); enumTest(OverTimeValues.B); enumTest(OverTimeValues.C); enumTest(OverTimeValues.A); enumTest(OverTimeValues.B); enumTest(OverTimeValues.C); enumTest(OverTimeValues.A); enumTest(OverTimeValues.B); enumTest(OverTimeValues.C); System.out.println("compareTo() : " + OverTimeValues.A.compareTo(OverTimeValues.B)); System.out.println("compareTo() : " + OverTimeValues.B.compareTo(OverTimeValues.A)); //enum 값들을 array로 리턴 for( OverTimeValues v : OverTimeValues.values() ) { System.out.println("values() : " + v); } } private static void enumTest(OverTimeValues time) { switch (time) { case A: System.out.println("AAAA :" + time.getAmount() ); break; case B: System.out.println("BBBB :" + time.getAmount() ); break; case C: System.out.println("CCCC :" + time.getAmount() ); break; } }
결과 :
Ctor called : 1000
Ctor called : 2000
Ctor called : 3000
AAAA :1000
BBBB :2000
CCCC :3000
AAAA :1000
BBBB :2000
CCCC :3000
AAAA :1000
BBBB :2000
CCCC :3000
compareTo() : -1
compareTo() : 1
values() : A
values() : B
values() : C
출처 : 자바의 신
'java' 카테고리의 다른 글
Throwable 및 stack trace의 이해 (0) | 2019.09.15 |
---|---|
try-catch finally (0) | 2019.09.15 |
interface와 abstract 차이 (0) | 2019.09.14 |
final class, final method, final variable (0) | 2019.09.14 |
Object class (0) | 2019.09.14 |