你不知道的Java--枚举(一)

2014-11-24 07:45:51 · 作者: · 浏览: 1

你不知道的Java环节,大部分采用dota作为背景,如有错误,请谅解并指正。

一:基本
[java]
public enum Hero {

AM,
BM,
AA;

}
这样,我们就把部分英雄放入到一个枚举中。
[java]
System.out.println(Hero.AA);
System.out.println(Hero.AM);
System.out.println(Hero.BM);

String a = Hero.AM.toString();
System.out.println(a);
//遍历一下枚举中的值
[java]
for (Hero h :Hero.values()){
System.out.println(h);
}


二:扩展一下
搞一个英雄类型,
[java]
public enum Type {

Agility("敏捷型"),
Power("力量型"),
Intelligence("智力型");

private String chinses;

private Type(String chinese){
this.chinses = chinese;
}

public String getChinses() {
return chinses;
}

public void setChinses(String chinses) {
this.chinses = chinses;
}


}
增加两个属性,构造方法(必须是private,或者不写,其他的就报错呀),
重写一下toString(),
[java]
public enum Hero {

AM("敌法师",Type.Agility),
BM("兽王",Type.Power),
AA("冰魂",Type.Intelligence);

private String name;
private Type type;

private Hero(String name,Type type) {
this.name = name;
this.type = type;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
// TODO Auto-generated method stub
return this.getType().getChinses()+"英雄:"+this.getName();
}

public Type getType() {
return type;
}

public void setType(Type type) {
this.type = type;
}

}


测试:
[java]
for (Hero h :Hero.values()){
System.out.println(h);
}

敏捷型英雄:敌法师
力量型英雄:兽王
智力型英雄:冰魂

三:看看这个有木有
多个构造方法,也是可以的。但是注意不要空指针了。
[java]
public enum Hero {

AM("敌法师",Type.Agility),
BM("兽王",Type.Power),
SS(),
AA("冰魂",Type.Intelligence);

private String name;
private Type type;

private Hero(String name,Type type) {
this.name = name;
this.type = type;
}

private Hero() {
// TODO Auto-generated constructor stub
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
// TODO Auto-generated method stub
return this.getType().getChinses()+"英雄:"+this.getName();
}

public Type getType() {
return type;
}

public void setType(Type type) {
this.type = type;
}

}

四:那这个呢

[java]
public interface Active {

void att();

}

[java]
public enum Hero implements Active{

AM("敌法师",Type.Agility),
BM("兽王",Type.Power),
// SS(),
AA("冰魂",Type.Intelligence);

private String name;
private Type type;

private Hero(String name,Type type) {
this.name = name;
this.type = type;
}

private Hero() {
// TODO Auto-generated constructor stub
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
// TODO Auto-generated method stub
return this.getType().getChinses()+"英雄:"+this.getName();
}

public Type getType() {
return type;
}

public void setType(Type type) {
this