\

해병 코딩

728x90
반응형

 

 


 

> enum 열거형 - 새로운 클래스 타입을 정의하는것
- 특정한 값만을 가질 수 있는 데이터 타입을 정의 할때 필요하다.


형식>
[접근지정자] enum 열거형이름 {  필요한 상수들 나열,..... }

 

 

package ex07.Enum;

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

public class EnumTest {
	  Day day;  //
	    
	    public EnumTest(Day day) {  //
	        this.day = day;
	    }
	    
	    public void tellItLikeItIs() {  
	        switch (day) {
	            case MONDAY:
	                System.out.println("Mondays are bad.");
	                break;
	                    
	            case FRIDAY:
	                System.out.println("Fridays are better.");
	                break;
	                         
	            case SATURDAY: case SUNDAY:
	                System.out.println("Weekends are best.");
	                break;
	                        
	            default:
	                System.out.println("Midweek days are so-so.");
	                break;
	        }
	    }
	    
	    public static void main(String[] args) {
	        EnumTest firstDay = new EnumTest(Day.MONDAY);
	        firstDay.tellItLikeItIs();
	        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
	        thirdDay.tellItLikeItIs();
	        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
	        fifthDay.tellItLikeItIs();
	        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
	        sixthDay.tellItLikeItIs();
	        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
	        seventhDay.tellItLikeItIs();
	 	       
	    }   
}






 

함수도 가질 수있다 

 

package ex07.Enum;

enum Operation {
    PLUS,
    MINUS,
    TIMES,
    DIVIDE;

    double calculate(double x, double y) {
        switch (this) {
            case PLUS:
                return x + y;
            case MINUS:
                return x - y;
            case TIMES:
                return x * y;
            case DIVIDE:
                return x / y;
            default:
                throw new AssertionError("Unknown operations " + this);
        }
    }
}

public class EnumTest2 {
	 public static void main(String[] args) {

	        double result = Operation.PLUS.calculate(1, 2);
	        System.out.println(result); //3.0
	    }

}

 

//열거형 예제

package ex07.Enum;

public enum WhoisRIR {
	ARIN("whois.arin.net"), 
	RIPE("whois.ripe.net"), 
	APNIC("whois.apnic.net"), 
	AFRINIC("whois.afrinic.net"), 
	LACNIC("whois.lacnic.net"), 
	JPNIC("whois.nic.ad.jp"), 
	KRNIC("whois.nic.or.kr"), 
	CNNIC("ipwhois.cnnic.cn"), 
	UNKNOWN("");
	
	private String url;
	WhoisRIR(String url) {		this.url = url;	}
	public String url() {		return url;	}
}

 

package ex07.Enum;

public class WhoisRIRMain {
	public static void main(String[] args) {
		System.out.println(WhoisRIR.ARIN.url());
		System.out.println(WhoisRIR.JPNIC.url());
	}
}


728x90
반응형

이 글을 공유합시다

facebook twitter googleplus kakaoTalk kakaostory naver band