java enum类型的字段 set_JAVA enum枚举类型的使用

1. 枚举类型的定义范围:

1)枚举类型可以是单独的一个class文件

/*** This enum is declared in the Season.java file.*/

public enumSeason {

WINTER,

SPRING,

SUMMER,

FALL

}

2)同样可以定义在其他类里面

public classDay {privateSeason season;publicString getSeason() {returnseason.name();

}public voidsetSeason(String season) {this.season =Season.valueOf(season);

}/*** This enum is declared inside the Day.java file and

* cannot be accessed outside because it's declared as private.*/

private enumSeason {

WINTER,

SPRING,

SUMMER,

FALL

}

}

3)但是不能定义在构造方法或普通方法体类,会报编译错误

public classDay {/*** Constructor*/

publicDay() {//Illegal. Compilation error

enumSeason {

WINTER,

SPRING,

SUMMER,

FALL

}

}public voidaSimpleMethod() {//Legal. You can declare a primitive (or an Object) inside a method. Compile!

int primitiveInt = 42;//Illegal. Compilation error.

enumSeason {

WINTER,

SPRING,

SUMMER,

FALL

}

Season season=Season.SPRING;

}

}

2.枚举类型注意事项

1)枚举中的元素不能重复

public enumSeason {

WINTER,

WINTER,//Compile Time Error : Duplicate Constants

SPRING,

SUMMER,

FALL

}

2)枚举中定义的常量默认都是public static final 修饰

3) jdk1.6及以下switch参数不能直接传递字符串,但可以可以使用enum类型

public static voidenumSwitchExample(Season s) {switch(s) {caseWINTER:

System.out.println("It's pretty cold");break;caseSPRING:

System.out.println("It's warming up");break;caseSUMMER:

System.out.println("It's pretty hot");break;caseFALL:

System.out.println("It's cooling down");break;

}

}

4)枚举类型中不能有public构造方法,但可以用私有的构造方法(默认为私有的)

public enumCoin {

PENNY(1), NICKEL(5), DIME(10), QUARTER(25); //usual names for US coins//note that the above parentheses and the constructor arguments match

private intvalue;

Coin(intvalue) {this.value =value;

}public intgetValue() {returnvalue;

}

}

5)枚举中可以有抽象方法,其中每一个类型可以单独实现该抽象方法

enumAction {

DODGE {public booleanexecute(Player player) {returnplayer.isAttacking();

}

},

ATTACK {public booleanexecute(Player player) {returnplayer.hasWeapon();

}

},

JUMP {public booleanexecute(Player player) {return player.getCoordinates().equals(new Coordinates(0, 0));

}

};public abstract booleanexecute(Player player);

}

还有一些其他的用法,没有一 一列举,可以参考地址:https://stackoverflow.com/documentation/java/155/enums#t=201708250625516795921;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值