1700445899
1700445900
(4)枚举可以自定义方法
1700445901
1700445902
这一点似乎并不是枚举的优点,类常量也可以有自己的方法呀,但关键是枚举常量不仅可以定义静态方法,还可以定义非静态方法,而且还能够从根本上杜绝常量类被实例化。比如我们要在常量定义中获得最舒服季节的方法,使用常量枚举的代码如下所示:
1700445903
1700445904
enum Season{
1700445905
1700445906
Spring, Summer, Autumn, Winter;
1700445907
1700445908
//最舒服的季节
1700445909
1700445910
public static Season getComfortableSeason(){
1700445911
1700445912
return Spring;
1700445913
1700445914
}
1700445915
1700445916
}
1700445917
1700445918
我们知道每个枚举项都是该枚举的一个实例,对于我们的例子来说,也就表示Spring其实是Season的一个实例,Summer也是其中一个实例,那我们在枚举中定义的静态方法既可以在类(也就是枚举Season)中引用,也可以在实例(也就是枚举项Spring、Summer、Autumn、Winter)中引用,看如下代码:
1700445919
1700445920
public static void main(String[]args){
1700445921
1700445922
System.out.println(“The most comfortable season is”+Season.getComfortableSeason());
1700445923
1700445924
}
1700445925
1700445926
那如果使用类常量要如何实现呢?代码如下:
1700445927
1700445928
class Season{
1700445929
1700445930
public final static int Spring=0;
1700445931
1700445932
public final static int Summer=1;
1700445933
1700445934
public final static int Autumn=2;
1700445935
1700445936
public final static int Winter=3;
1700445937
1700445938
//最舒服的季节
1700445939
1700445940
public static int getComfortableSeason(){
1700445941
1700445942
return Spring;
1700445943
1700445944
}
1700445945
1700445946
}
1700445947
1700445948
想想看,我们要怎么才能打印出“The most comfortable season is Spring”这句话呢?除了使用switch判断外没有其他办法了。
[
上一页 ]
[ :1.700445899e+09 ]
[
下一页 ]