Skip to content

Commit 9f7d36d

Browse files
committed
enums
1 parent 65d669c commit 9f7d36d

File tree

2 files changed

+157
-0
lines changed

2 files changed

+157
-0
lines changed

app/data/authors.yaml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,11 @@
7474
nine textbooks on software programming. Most recently, she is a contributing author to
7575
The Definitive Guide to Modern Java Clients with JavaFX 17. Gail has presented at various
7676
Java conferences and JUGS including Devoxx, DevNexus, JCrete, and Oracle Code/JavaOne worldwide.
77+
78+
- name: Daniel Schmid
79+
github: danthe1st
80+
twitter: dan_the_1st
81+
photo_url: https://danthe1st.github.io/img/Daniel.jpg
82+
website: https://danthe1st.github.io/
83+
description: |
84+
Daniel is a Java Developer from Austria who is also managing an online Java User Group.
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
---
2+
id: lang.classes-objects.enums
3+
title: Enumerations
4+
slug: learn/classes-objects/enums
5+
type: tutorial-group
6+
group: classes_objects
7+
layout: learn/tutorial-group.html
8+
subheader_select: tutorials
9+
main_css_id: learn
10+
description: "Working with enumerations."
11+
last_update: 2023-09-28
12+
author: ["DanielSchmid"]
13+
---
14+
## What are enums?
15+
Enums are classes where all instances are known to the compiler.
16+
They are used for creating types that can only have few possible values.
17+
18+
Enums can be created similar to classes but use the `enum` keyword instead of `class`.
19+
In the body, there is a list of instances of the enum named enum constants which are seperated by `,`.
20+
No instances of the enum can be created outside of enum constants.
21+
22+
```java
23+
public enum DayOfWeek {
24+
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
25+
}
26+
```
27+
28+
All enums implicitely extend `java.lang.Enum` and cannot have any subclasses.
29+
30+
## Accessing and comparing enums
31+
The values of an enum can be used as constants.
32+
In order to check whether two instances of an enum are the same, the `==` operator can be used.
33+
```java
34+
DayOfWeek weekStart = DayOfWeek.MONDAY;
35+
36+
if (weekStart == DayOfWeek.MONDAY) {
37+
System.out.println("The week starts on Monday.");
38+
}
39+
```
40+
41+
It is also possible to use `switch` for performing actions depending on the value of the enum.
42+
43+
```java
44+
DayOfWeek someDay = DayOfWeek.FRIDAY;
45+
46+
switch (someDay) {
47+
case MONDAY:
48+
System.out.println("The week just started.");
49+
break;
50+
case TUESDAY:
51+
case WEDNESDAY:
52+
case THURSDAY:
53+
System.out.println("We are somewhere in the middle of the week.");
54+
break;
55+
case FRIDAY:
56+
System.out.println("The weekend is near.");
57+
break;
58+
case SATURDAY:
59+
case SUNDAY:
60+
System.out.println("Weekend");
61+
break;
62+
default:
63+
throw new AssertionError("Should not happen");
64+
}
65+
```
66+
67+
With [Switch Expressions](id:lang.classes-objects.switch-expression),
68+
the compiler can check whether all values of the enum are handled.
69+
```java
70+
DayOfWeek someDay = DayOfWeek.FRIDAY;
71+
72+
String text = switch (someDay) {
73+
case MONDAY -> "The week just started.";
74+
case TUESDAY, WEDNESDAY, THURSDAY -> "We are somewhere in the middle of the week.";
75+
case FRIDAY -> "The weekend is near.";
76+
case SATURDAY, SUNDAY -> "Weekend";
77+
};
78+
79+
System.out.println(text);
80+
```
81+
82+
## Adding members to enums
83+
84+
Just like classes, enums can have constructors, methods and fields.
85+
In order to add these, it is necessary to add a `;` after the list of enum constants.
86+
Arguments to the constructor are passed in parenthesis after the declaration of the enum constant.
87+
88+
```java
89+
public enum DayOfWeek {
90+
MONDAY("MON"), TUESDAY("TUE"), WEDNESDAY("WED"), THURSDAY("THU"), FRIDAY("FRI"), SATURDAY("SAT"), SUNDAY("SUN");
91+
92+
private final String abbreviation;
93+
94+
DayOfWeek(String abbreviation) {
95+
this.abbreviation = abbreviation;
96+
}
97+
98+
public String getAbbreviation() {
99+
return abbreviation;
100+
}
101+
}
102+
```
103+
104+
## Special methods
105+
All enums have a few methods that are added implicitely.
106+
107+
For example, the method `name()` is present in all enum instances and can be used to get the name of the enum constant.
108+
Similarly, a method named `ordinal()` returns the position of the enum constant in the declaration.
109+
```java
110+
System.out.println(DayOfWeek.MONDAY.name());//MONDAY
111+
System.out.println(DayOfWeek.MONDAY.ordinal());//0 because MONDAY is the first constant in the DayOfWeek enum
112+
```
113+
114+
Aside from instance methods, there are also static methods added to all enums.
115+
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+
```
117+
DayOfWeek[] days = DayOfWeek.values();//all days of the week
118+
DayOfWeek monday = DayOfWeek.valueOf("MONDAY");
119+
```
120+
121+
## Using enums for singletons
122+
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+
```java
124+
public enum SomeSingleton {
125+
INSTANCE;
126+
//fields, methods, etc.
127+
}
128+
```
129+
130+
## Abstract methods in enums
131+
Even though enums cannot be extended, they can still have `abstract` methods. In that case, an implementation must be present in each enum constant.
132+
```java
133+
enum MyEnum {
134+
A() {
135+
@Override
136+
void doSomething() {
137+
System.out.println("a");
138+
}
139+
},
140+
B() {
141+
@Override
142+
void doSomething() {
143+
System.out.println("b");
144+
}
145+
};
146+
147+
abstract void doSomething();
148+
}
149+
```

0 commit comments

Comments
 (0)