IT/Spring

Enum(이늄)

바바옄 2015. 4. 27. 16:52
반응형

EnumTest.java (Class)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 상수보다 ENUM으로 쓰는 것이 더 안전하다.
 
public class EnumTest {
 
    public static void main(String[] args){
        
        // enum으로 상수를 정의하여 메소드 호출시
        showAnimal(Animal.DOG);
        // 다른 enum은 사용할 수 없다.
        //showAnimal(Car.HYUNDAI);
        
        // 인터페이스로 상수를 정의하여 메소드 호출시
        // 잘못된 값이 출력될 수 있다.
        showAnimal2(Person.MEN);
        showAnimal2(Animals.BIRD);
    }
    
    public static void showAnimal(Animal animal){
        
        if(animal == Animal.CAT){
            System.out.println("고양이");
            System.out.println(animal.value);
            System.out.println(animal.value2);
        }
        else if(animal == Animal.DOG){
            System.out.println("강아지");
            System.out.println(animal.value);
            System.out.println(animal.value2);
        }
        else if(animal == Animal.BIRD){
            System.out.println("새");
            System.out.println(animal.value);
            System.out.println(animal.value2);
        }
        else{
            System.out.println("???");
        }
    }
    
    /*
     * a 인터페이스와 b 인터페이스의 상수 타입이 같을때
     * 두 인터페이스가 같은 메소드를 호출하게 되면 잘못된 값이 나올 수도 있다.  
     */
    public static void showAnimal2(int animals){
        
        if(animals == Animals.CAT){
            System.out.println("고양이");
        }
        else if(animals == Animals.DOG){
            System.out.println("강아지");
        }
        else if(animals == Animals.BIRD){
            System.out.println("새");
        }
        else{
            System.out.println("???");
        }
    }
}
 
cs

 

Animal.java(Enum)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 인터페이스에서 상수를 쓰는 대신, ENUM을 사용.
// 상수보다 ENUM으로 쓰는 것이 더 안전하다.
 
public enum Animal {
    
    CAT("야옹","나비"), DOG("멍멍","바둑이"), BIRD("짹짹","참새");
    
    String value = "";
    String value2= "";
    Animal(String value, String value2){
        this.value = value;
        this.value2 = value2;
    }
}
 
cs

 

Car.java(Enum)

1
2
3
4
5
6
// 인터페이스에서 상수를 쓰는 대신, ENUM을 사용.
 
public enum Car {
    HYUNDAI, SM, KIA;
}
 
cs

 

Animals.java(interface)

1
2
3
4
5
6
7
8
9
10
// 인터페이스에서 상수 쓰는 방법
 
public interface Animals {
    
    public static final int CAT = 0;
    public static final int DOG = 1;
    public static final int BIRD = 2;
 
}
 
cs

 

Person.java(interface)

1
2
3
4
5
6
7
8
// 인터페이스에서 상수 쓰는 방법
 
public interface Person {
 
    public static final int MEN = 0;
    public static final int WOMEN = 1
}
 
cs
반응형