Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
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
Archives
Today
Total
04-25 06:18
관리 메뉴

zyint's blog

Java 5.0 Enum 사용 본문

예전글들

Java 5.0 Enum 사용

진트­ 2007. 2. 27. 11:26
enum
Java 1.5 has built-in support for enumerated types. Prior to that you had to kludge them in some way with static final ints (which were not typesafe) or with Objects which would not work in switch statements.

Don't confuse enum with the Enumeration interface, an almost obsolete way of iterating over Collections, replaced by Iterator.

Java 1.5 enums are references to a fixed set of Objects than represent the various possible choices. Enums handle single choices, not combinations of choices. For combinations, you need EnumSet.

Enums and the enum constants are just classes. Normally they should be capitalised. However, since the constant name is the same as what is displayed externally, I gather the capitalisation rules are relaxed. You would name your constants with upper or lower case names as appropriate for the application.

Needless to say, these enums are type safe. If you try to store a code for a dog Breed into a Locomotive type enum variable, the compiler will refuse.


enum Breed { 
// the enum constants
Dalmatian ( "spotted" )
, Labrador ( "black" )
, Dachshund( "brown" );
// constructor
Breed ( String colour ) {
this.colour = colour;
}
private String colour;
// additional method of every Breed object
public String getColour() {
return colour;
}
}
-----------------------client 사용
System.out.println( Breed.Dachshund ):
Comments