-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnumAdvanced.java
65 lines (50 loc) · 1.38 KB
/
EnumAdvanced.java
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
package concept.examples.enums;
public class EnumAdvanced {
// Enum with a variable,method and constructor
enum SeasonCustomized {
WINTER(1), SPRING(2), SUMMER(3), FALL(4);
// variable
private int code;
// method
public int getCode() {
return code;
}
// Constructor-only private or (default)
// modifiers are allowed
SeasonCustomized(int code) {
this.code = code;
}
// Getting value of enum from code
public static SeasonCustomized valueOf(int code) {
for (SeasonCustomized season : SeasonCustomized.values()) {
if (season.getCode() == code)
return season;
}
throw new RuntimeException("value not found");// Just for kicks
}
// Using switch statement on an enum
public int getExpectedMaxTemperature() {
switch (this) {
case WINTER:
return 5;
case SPRING:
case FALL:
return 10;
case SUMMER:
return 20;
}
return -1;// Dummy since Java does not recognize this is possible :)
}
}
public static void main(String[] args) {
SeasonCustomized season = SeasonCustomized.WINTER;
/*
* //Enum constructor cannot be invoked directly //Below line would
* cause COMPILER ERROR SeasonCustomized season2 = new
* SeasonCustomized(1);
*/
System.out.println(season.getCode());// 1
System.out.println(season.getExpectedMaxTemperature());// 5
System.out.println(SeasonCustomized.valueOf(4));// FALL
}
}