java 枚举继承 扩展_Java中的枚举继承?

您不能从另一个枚举继承枚举,尽管您可以让您的枚举实现一个接口.技术问题(所有枚举隐式扩展java.lang.Enum,因此它们不能扩展另一个类,只实现额外的接口)并非偶然:

For the most part, extensibility of enums turns out to

be a bad idea. It is confusing that elements of an extension type are instances of

the base type and not vice versa. There is no good way to enumerate over all of the

elements of a base type and its extension. Finally, extensibility would complicate

many aspects of the design and implementation.

但是,我并不完全理解你的问题:你没有使用values()来迭代你的枚举吗?那么你不应该担心用新值扩展你的枚举.

请更清楚地说明“破碎”应该是什么意思.

更新:所以你需要为不同类型的星星设置不同的波段组 – 这可以使用扩展公共接口的不同枚举来实现,例如:

interface Band {

String getName();

void doStuff();

...

}

enum BandsVI implements Band {

V, I;

public String getName() { return toString(); }

public void doStuff() { /* do stuff as appropriate for these bands */ }

...

}

enum BandsJHK implements Band {

J, H, K;

public String getName() { return toString(); }

public void doStuff() { /* do stuff as appropriate for these bands */ }

...

}

你可以通过使你的Star类通用来使用它们:

class Star & Band> {

private Class bandType;

public Star(Class bandType) { this.bandType = bandType; }

public void printBandNames() {

for (Band b : bandType.getEnumConstants())

System.out.println(b.getName());

}

public void doStuffOnAllBands() {

for (Band b : bandType.getEnumConstants())

b.doStuff();

}

}

...

Star star1 = new Star(BandsVI.class);

Star star2 = new Star(BandsJHK.class);

star1.printBandNames(); // prints V I

star2.printBandNames(); // prints J H K

如果乐队被组织成不同的组,这很好地工作.但是,如果有混合波段组的星星,您可能更喜欢另一种方法:

class Star {

private List extends Band> bandTypes;

public Star(List extends Band> bandTypes) { this.bandTypes = bandTypes; }

public void printBandNames() {

for (Band b : bandTypes)

System.out.println(b.getName());

}

...

}

...

Star star1 = new Star(Arrays.asList(BandsVI.values()));

Star star3 = new Star(Arrays.asList(new Band[]{BandsVI.V, BandsVI.I, BandsJHK.K}));

...

这允许您设置具有任意混合波段的星星.但是,这样您就无法在乐队上使用EnumSet或EnumMap.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值