본문 바로가기

JavaNote

enum

반응형

 

enumeration 열거

: grouping constants together.

> 예) BodyType이란 field define시 여러개 비슷한 상수를 store하기 좋음.

> 예) 요일이란 field define시 (월,화,수,목,금,토,일) 상수를 store하기 좋음.

 
대문자로 씀,
index는 0,1,2,3,4.....

https://inor.tistory.com/12  기본개념

 

 

간단예시. ...........Set Challenge에서 발췌

public class Enum {


    enum BodyTypes {     // field(BodyType) // enum이용해서 상수 여러개 저장   V
        STAR,
        PLANET,
        DWARF_PLANET,
        MOON,
        COMET,
        ASTEROID
    }



    public static void main(String[] args) {

        BodyTypes star = BodyTypes.STAR;
        System.out.println(star);

    }
}			// -> Output : STAR

 

또다른 예시

public abstract class HeavenlyBody {
    private final BodyType bodyType;                      //field	V
    private final double orbitalPeriod;
    private final Set<HeavenlyBody> satellites;

    public enum BodyTypes {     // field(BodyType) // enum이용해서 상수 여러개 저장   V
        STAR,
        PLANET,
        DWARF_PLANET,
        MOON,
        COMET,
        ASTEROID
    }

    //constructor
    public HeavenlyBody(String name, double orbitalPeriod, BodyTypes bodyType) {

        this.name = name; 
        this.orbitalPeriod = orbitalPeriod;
        this.satellites = new HashSet<>();
    	this.bodyType = bodyType;     // field bodyType(enum) initialization    V
    }
//getter
    public double getOrbitalPeriod() {
        return orbitalPeriod;
		 }
 .
 .
 .
 .
 
}

Key값에다가

public abstract class HeavenlyBody {
    private final Key key;                          //field
    private final double orbitalPeriod;
    private final Set<HeavenlyBody> satellites;

    public enum BodyTypes {     // field(BodyType) // enum이용해서 상수 여러개 저장   V
        STAR,
        PLANET,
        DWARF_PLANET,
        MOON,
        COMET,
        ASTEROID
    }

    //constructor
    public HeavenlyBody(String name, double orbitalPeriod, BodyTypes bodyType) {

        this.key = new Key(name, bodyType); // field bodyType(enum) initialization
        this.orbitalPeriod = orbitalPeriod;
        this.satellites = new HashSet<>();
    }
//getter
    public double getOrbitalPeriod() {
        return orbitalPeriod;
		 }
 .
 .
 .
 .
 
}