열거상수는 하나하나가 객체이다. 클래스와 비슷함.
클래스는 외부에서 new 로 객체 생성해야하지만, 열거상수는 자체적으로 생성자를 호출함.
매개변수가 없고, 필드가 없어서 인지하지 못했을 뿐 컴파일러가 default 생성자 생성해줌.
필드, 메소드도 호출할 수 있다.
(열거상수 다음에 다른 메소드나 생성자가 나올 경우 마지막 열거상수에는 세미콜론이 필요함.
enum에 생성된 필드는 열거상수 객체에 소속됨.)
import lombok.extern.log4j.Log4j;
@Log4j
public class EnumEx {
public static void main(String[] args) {
Week today = Week.MONDAY;
Week today2 = Week.SATURDAY;
log.info(today);
log.info(today2);
log.info(today.ordinal());
log.info(today2.ordinal());
log.info(today.getName());
log.info(today.getAge());
}// main
}// end class
enum Week { //한 클래스 내에서 public은 한 번만 쓸 수 있다. class에 붙였기 때문에 enum엔 못붙임
// Ordinal number started with 1
MONDAY("NAME_1", 10),
TUESDAY("NAME_2", 20),
WEDNSEDAY("NAME_3", 30),
THURSDAY("NAME_4", 40),
FRIDAY("NAME_5", 50),
SATURDAY("NAME_6", 60),
SUNDAY("NAME_7", 70); //열거상수 외에 다른생성자, 메소드 등 작성할 땐 세미콜론 필수
//Illegal modifier for the enum constructor;
// only private is permitted. >>public 으로 했을 때 발생하는 오류메세지.
Week(){
System.out.println("default constructor invoked.");
} //default constructor
private String name; //열거상수 객체의 필드
private int age;
// only private is permited
private Week(String name, int age) {
System.out.printf("constructor(%s, %d) invoked. \n", name, age);
this.name = name;
this.age = age;
} // constructor
public String getName() {
System.out.println("getValue() invoked.");
System.out.println("\t+ this: " + this);
System.out.println("\t+ type : " + this.getClass().getName()); //getClass >> clazz객체 얻기
return this.name;
} // getValue
public int getAge() {
System.out.println("getName() invoked.");
System.out.println("\t+ this : " + this);
System.out.println("\t+ type : " + this.getClass().getName());
return this.age;
} // getName
} // end enum