W3schools - Enum
이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다
찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요
enums
enum(enumerations) is a special class that represents a group of constants
To create enum use the “enum” keyword, and weparate the constants with a comma,
they should be in uppercase letters
public class Main{ // can have enum inside a class
enum Level{
LOW,
MEDIUM,
HIGH
}
public static void main(String[] args){
Level myVar = Level.MEDIUM; // Can access enum constants with the dot syntax
System.out.print(myVar); // output MEDIUM
switch(myVar){ // are often used in “switch“ to check for corresponding values
case LOW:
System.out.println(“Low level”);
break;
case MEDIUM:
System.out.println(“Medium level”); // output Medium level
break;
default:
System.out.println(“High level”);
break;
for(Level myVar : Level.values()){
// enum has a values() method, which returns an array of all enum constants
System.out.println(myVar);
}
}
}
Difference between Enums and Classes
enum can, just like a class, have attributes and methods
only difference is that enum constants are public static, and final
so, use enum when you have values that aren’t going to change