You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
System.out.println(DayOfWeek.MONDAY.ordinal());//0 because MONDAY is the first constant in the DayOfWeek enum
125
+
System.out.println(DayOfWeek.MONDAY.name());// prints "MONDAY"
126
+
System.out.println(DayOfWeek.MONDAY.ordinal());// prints "0" because MONDAY is the first constant in the DayOfWeek enum
112
127
```
113
128
114
129
Aside from instance methods, there are also static methods added to all enums.
115
130
The method `values()` returns an array containing all instances of the enum and the method `valueOf(String)` can be used to get a specific instance by its name.
116
131
```java
117
-
DayOfWeek[] days =DayOfWeek.values();//all days of the week
132
+
DayOfWeek[] days =DayOfWeek.values();//all days of the week
118
133
DayOfWeek monday =DayOfWeek.valueOf("MONDAY");
119
134
```
120
135
136
+
<aid="singletons"> </a>
121
137
## Using enums for singletons
138
+
122
139
Since enums can only have a specific number of instances, it is possible to create a singleton by creating an enum with only a single enum constant.
123
140
```java
124
141
publicenumSomeSingleton {
125
-
INSTANCE;
126
-
//fields, methods, etc.
142
+
INSTANCE;
143
+
//fields, methods, etc.
127
144
}
128
145
```
129
146
147
+
<aid="abstract"> </a>
130
148
## Abstract methods in enums
149
+
131
150
Even though enums cannot be extended, they can still have `abstract` methods. In that case, an implementation must be present in each enum constant.
0 commit comments