'2019/04/10'에 해당되는 글 1건

Java Enum 이란?

개발이야기 2019. 4. 10. 15:31
ddㅇJava Enum이란? 
JDK1.5 부터 관련이 있는 상수들의 집합을 사용할때 enum을 사용한다. 
enum은 인터페이스가 아니고 완전한 클래스이다. 
enum의 장점
- 코드가 간결하고 가독성이 좋다.
- 인스턴스의 생성과 상속을 방지한다.
- 키워드에 구현의도가 나열되어있다. (enumeration)

d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
enum Type {
    WALKING, RUNNING, TRACKING, HIKING
}
 
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        for(Type type : Type.values()) {
            System.out.println(type);
        }
    }
}

cs


enum Type은 아래와 같은 코드와 같다. 


1
2
3
4
5
6
7
8
9
10
11
 
enum Type {
    WALKING, RUNNING, TRACKING, HIKING
}
class Type {
    public static final Type WALKING = new Type();
    public static final Type WALKING = new Type();
    public static final Type WALKING = new Type();
    private Type() {
    }
}

cs


생성자의 접근제어가 private 이고 클래스를 다른용도로 사용하는것을 금지한다. 


출력결과


WALKING
RUNNING
TRACKING
HIKING

enum과 생성자활용



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public enum BoardType {
 
    notice("공지사항"),
    free("자유게시판");
 
    BoardType(String value) {
        this.value = value;
    }
    
    private String value;
 
    public String getValue() {
        return this.value;
    }
 
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
enum Fruit{
    APPLE("red"), PEACH("pink"), BANANA("yellow");
    private String color;
    Fruit(String color){
        System.out.println("Call Constructor "+this);
        this.color = color;
    }
    String getColor(){
        return this.color;
    }
}
 
enum Company{
    GOOGLE, APPLE, ORACLE;
}
 
public class ConstantDemo {
     
    public static void main(String[] args) {
        for(Fruit f : Fruit.values()){
            System.out.println(f+", "+f.getColor());
        }
    }
}

cs



 참고링크 


https://opentutorials.org/module/516/6091

http://www.nextree.co.kr/p11686/

https://sjh836.tistory.com/134


봐두면 좋은 링크

Java Enum 활용기 

블로그 이미지

클라인STR

,