pooney
article thumbnail
Published 2020. 6. 28. 17:21
Java Enum 이란? Java

우리는 일반적으로 어떠한 상수를 정의하고 할때 public static final 이란 키워드를 사용하여 정의를 할 것입니다 . final이란 키워드로 정의를 하면 값을 수정 , 변경 할 수 없습니다. 

 

 

fianl

 

fianl이란 키워드를 통한 상수를 정의를 하고 값을 넣을 것입니다. 

 

<java />
public final static int book=0; public final static int computer=1; public final static int phone=2;

 

아니면 클래스 타입의 객체를 선언해서 사용하는 방법이 존재합니다.

 

1. Product.class 

<java />
public class Product { public final static Product book = new Product(); public final static Product computer = new Product(); public final static Product phone = new Product(); }

 

2. Main.class

 

swtich문을 사용하여 비교를 하면 book이 출력되는 것을 확인 할 수 있습니다.

<java />
public class Main { public static final int book = 1; public static final int computer = 2; public static final int phone = 3; public static void main(String[] args) { int type = book; switch (type){ case book: System.out.println("book"); break; case computer: System.out.println("computer"); break; case phone: System.out.println("phone"); break; } } }

 

 

객체를 사용하여 상수정의 

 

3. Product

<java />
public class Product { public static final Product book = new Product(); public static final Product computer = new Product(); public static final Product phone = new Product(); }

 

4.  

5. Main

 

swtich로 값을 비교하고자 할때 에러가 발생할 것입니다. switch문은 가독성을 높일 수 있는 방법이지만 인스턴스를 비교는 할수가 없다. 원시형 타입 이나 , enum등의 타입을 넣어야합니다.  때문에 컴파일에러가 발생한다.  비교하고자 할때는 if문을 사용해야합니다. 

 

<java />
public class Main { public static void main(String[] args) { Product type = Product.book; //컴파일 에러 발생 switch (type){ case Product.book: System.out.println("book"); break; case Product.computer: System.out.println("computer"); break; case Product.phone: System.out.println("phone"); break; } } }

 

 

 

 

또다른 방법은 interface를 사용하는 것입니다. 

 

 

 

 

 

interface

6.  

7. ProductInterface

 

interface에 존재하는 필드는 public final static이 암시적으로 사용되어 바로 접근 가능합니다. 

<java />
public interface ProductInterface { int book=0; int computer =1; int phone =2; }

 

8. Main

<java />
public class Main { public static void main(String[] args) { int type = ProductInterface.book; switch (type){ case ProductInterface.book: System.out.println("book"); break; case ProductInterface.computer: System.out.println("computer"); break; case ProductInterface.phone: System.out.println("phone"); break; } } }

 

마지막 방법은 Enum을 사용하여 상수 정의를 하는 것입니다.

 

 

Enum

 

Enum은 기존에 상수를 정의 하는 public static final , interface 등을 통하여 작성하는 것 보다 코드가 간결하고 , 인스턴스 생성과 상속을 방지합니다.. 

 

 

9. ProductEnum

<java />
public enum ProductEnum { BOOK , COMPUTER, PHONE }

 

Enum  동작은 기존 아래의 방법과 동일하기 작동한다고 보면됩니다 그이유는 Enum 또한 클래스이며 생성자를 가질 수 있기 때문입니다. 열겨형으로 우리가 BOOK , COMPUTER, PHONE 을 하나하나 만들때마다 new ProductEnum 이라는  인서턴스화 하는 과정이 동작하고 new 인스턴스화하면 생성자가 호출이되는데 enum에 열거된 상수만큼 생성자를 호출하게 되는 것입니다

 

10. Product

<java />
public class Product { public static final Product book = new Product(); public static final Product computer = new Product(); public static final Product phone = new Product(); }

 

11. main

switch문의 case 의 타입을 보면 타입이 아닌 상수가 적혀있는 것을 확인 할 수 있습니다. 이유는 값을 swtich문에 던질때 이미 ProductEnum 이란것을 알 기 때문에 생략이 가능 한 것 입니다.

<java />
public class Main { public static void main(String[] args) { ProductEnum type = ProductEnum.BOOK; switch (type){ case BOOK: System.out.println("book"); break; case COMPUTER: System.out.println("computer"); break; case PHONE: System.out.println("phone"); break; } } }

 

Enum 생성자 정의

 

 

12. ProductEnum

<java />
public enum ProductEnum { BOOK, COMPUTER, PHONE; ProductEnum(){ System.out.println("call me !! " + this); } }

 

 

13. main

<java />
public class Main { public static void main(String[] args) { ProductEnum type = ProductEnum.BOOK; switch (type){ case BOOK: System.out.println("book"); break; case COMPUTER: System.out.println("computer"); break; case PHONE: System.out.println("phone"); break; } } }

 

 

14. console 

 

위에 설명한 것 처럼  Enum은 클래스이기 때문에 생성자를 가질 수 있어 "call me !! {상수}"  가 3번 호출되는 것을 확인 할 수 있습니다. 또한 Enum의 상수에는 변수를 지정 하거나 메소드를 정의 할 수 있습니다. 

 

 

Enum의 상수에 변수정의 와 메소드 정의

15. ProductEnum

<java />
public enum ProductEnum { BOOK("책"), COMPUTER("컴퓨터"), PHONE("핸드폰"); private String name; public String getName(){ return this.name; } ProductEnum(String name){ this.name = name; } }

 

16. main 

<java />
public class Main { public static void main(String[] args) { String name = ProductEnum.BOOK.getName(); //ex) 책 } }

 

'Java' 카테고리의 다른 글

Java 인스턴스 변수와 정척 초기화 블록  (0) 2020.08.17
Java 날짜 연산 LocalDateTime  (0) 2020.06.28
Java 출력스트림  (0) 2020.06.21
Java 동적으로 객체 생성하기  (0) 2020.06.21
profile

pooney

@pooney

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!