Skip to content

Commit 4ab63d2

Browse files
committed
feat: add java enum demo
1 parent aee250d commit 4ab63d2

4 files changed

Lines changed: 108 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.wdbyte.enum2;
2+
3+
/**
4+
* 计算枚举类
5+
*/
6+
public enum Calc {
7+
// 加法
8+
PLUS {
9+
public int apply(int x, int y) {
10+
return x + y;
11+
}
12+
},
13+
// 减法
14+
MINUS {
15+
public int apply(int x, int y) {
16+
return x - y;
17+
}
18+
},
19+
// 乘法
20+
MULTIPLY {
21+
public int apply(int x, int y) {
22+
return x * y;
23+
}
24+
};
25+
26+
public int apply(int x, int y){
27+
// todo
28+
return x + y;
29+
}
30+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.wdbyte.enum2;
2+
3+
/**
4+
* @author niulang
5+
* @date 2023/05/01
6+
*/
7+
public class CalcTest {
8+
public static void main(String[] args) {
9+
// 加法
10+
int res = Calc.PLUS.apply(2, 3);
11+
System.out.println(res);
12+
// 减法
13+
res = Calc.MINUS.apply(2, 3);
14+
System.out.println(res);
15+
// 乘法
16+
res = Calc.MULTIPLY.apply(2, 3);
17+
System.out.println(res);
18+
}
19+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.wdbyte.enum2;
2+
3+
/**
4+
* 矩形枚举类
5+
*/
6+
public enum Rectangle implements Shape {
7+
SMALL(3, 4),
8+
MEDIUM(4, 5),
9+
LARGE(5, 6);
10+
11+
private int length;
12+
private int width;
13+
14+
Rectangle(int length, int width) {
15+
this.length = length;
16+
this.width = width;
17+
}
18+
19+
public double getArea() {
20+
return length * width;
21+
}
22+
23+
public static void main(String[] args) {
24+
Shape shape = Rectangle.LARGE;
25+
double shapeArea = shape.getArea();
26+
System.out.println(shapeArea);
27+
}
28+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.wdbyte.enum2;
2+
3+
/**
4+
* @author niulang
5+
* @date 2023/05/01
6+
*/
7+
public class WeekdayTest {
8+
public static void main(String[] args) {
9+
Weekday day = Weekday.MONDAY;
10+
if (day == Weekday.MONDAY) {
11+
System.out.println("Today is Monday.");
12+
}
13+
14+
15+
Weekday[] weekdays = Weekday.values();
16+
for (Weekday weekday : weekdays) {
17+
System.out.println(weekday);
18+
}
19+
20+
for (Weekday weekday : weekdays) {
21+
System.out.println(weekday.ordinal());
22+
}
23+
Weekday monday = Weekday.MONDAY;
24+
switch (monday){
25+
case MONDAY :{System.out.println("周一");break;}
26+
case SUNDAY :{System.out.println("周末");break;}
27+
}
28+
System.out.println(Weekday.valueOf("MONDAY"));
29+
System.out.println(Weekday.valueOf("MONDAY1"));
30+
}
31+
}

0 commit comments

Comments
 (0)