Repository navigation
Expand file tree
/
Copy pathEnumExample.java
More file actions
74 lines (61 loc) · 1.66 KB
/
Copy pathEnumExample.java
File metadata and controls
74 lines (61 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package Snippets;
import java.io.Serializable;
// extends enum class by default
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public class EnumExample {
public static void main(String[] args) {
// Get all enum values
for (Day d : Day.values()) {
System.out.println(d + " is at index " + d.ordinal());
}
// Convert string to enum
Day day = Day.valueOf("FRIDAY");
System.out.println("Converted: " + day);
}
}
enum Size implements Serializable {
SMALL(28), MEDIUM(32), LARGE(36), XLARGE(40);
private final int sizeValue;
// Constructor
Size(int sizeValue) {
this.sizeValue = sizeValue;
}
public int getSizeValue() {
return sizeValue;
}
}
class EnumWithFields {
public static void main(String[] args) {
Size mySize = Size.LARGE;
System.out.println("Size: " + mySize + ", Value: " + mySize.getSizeValue());
}
}
enum Operation {
ADD {
@Override
public int apply(int a, int b) {
return a + b;
}
},
MULTIPLY {
@Override
public int apply(int a, int b) {
return a * b;
}
};
// Abstract method
public abstract int apply(int a, int b);
//custom method
public void displayOperation() {
System.out.println("Current operation: " + this);
}
}
class EnumWithAbstractMethod {
public static void main(String[] args) {
System.out.println("10 + 5 = " + Operation.ADD.apply(10, 5));
System.out.println("10 * 5 = " + Operation.MULTIPLY.apply(10, 5));
Operation.ADD.displayOperation();
}
}