본문 바로가기

개발하자/JAVA중급

enum(열거형) : 상수값만을 모아서 선언한것

# enum(열거형) : 상수값만을 모아서 선언한것


[ex] 실행결과는?
class Color{
public static final int Red=1;
public static final int Green=2;
public static final int Blue=3;
int rgb;
void setValue(int v){ rgb=v; }
String getValue(){
String c="";
switch(rgb){
case 1 : c="빨강";break;
case 2 : c="초록";break;
case 3 : c="파랑";break;
}
return c;
}
}
class A{
public static void main(String args[]){
Color c=new Color();
c.setValue(100);
System.out.println(c.getValue());
}
}


[ex] 위소스코드의 문제점을 해결하려면...

enum Color{
Red, Green, Blue
}
class ColorTable{
Color color;
void setValue(Color color){
this.color=color;
}
String getValue(){
String c="";
switch(color){
case Red : c="빨강";break;
case Green : c="초록";break;
case Blue : c="파랑";break;
}
return c;
}
}
class A{
public static void main(String args[]){
ColorTable c=new ColorTable();
c.setValue(Color.Red);
System.out.println(c.getValue());
}
}

[ex]
class ColorTable{
enum Color{Red, Green, Blue} // enum이 클래스내에 선언된 경우

Color color;
void setValue(Color color){
this.color=color;
}
String getValue(){
String c="";
switch(color){
case Red : c="빨강";break;
case Green : c="초록";break;
case Blue : c="파랑";break;
}
return c;
}
}
class A{
public static void main(String args[]){
ColorTable c=new ColorTable();
c.setValue(ColorTable.Color.Red); // 위소스코드와 다른부분
System.out.println(c.getValue());
}
}

[ex]
class ColorTable{
enum Color{Red, Green, Blue}

public static void main(String args[]){
System.out.println(Color.Red.ordinal()); // 0
System.out.println(Color.Green.ordinal()); // 1
System.out.println(Color.Blue.ordinal()); // 2
}
}


[ex]
class ColorTable{
enum Color{Red, Green, Blue}

public static void main(String args[]){
Color[] colorArr=Color.values();
for( Color c: colorArr)
System.out.println(c);
}
}



[ex]
class ColorTable{
enum Color{
Red("빨강"), Green("초록"), Blue("파랑");

String c;
Color(String c){
this.c=c;
}
public String toString(){
return c;
}
}
public static void main(String args[]){
Color[] colorArr=Color.values();
for( Color c: colorArr)
System.out.println(c);
}
}




[ex]
class ColorTable{
enum Color{
Red("빨강"),
Green("초록"){
public String toString(){
return "녹색";
}
},
Blue("파랑");

String c;
Color(String c){
this.c=c;
}
public String toString(){
return c;
}
}

public static void main(String args[]){
Color[] colorArr=Color.values();
for( Color c: colorArr)
System.out.println(c);
}
}