枚举可以被子类化以添加新元素吗? [英] Can enums be subclassed to add new elements?

查看:23
本文介绍了枚举可以被子类化以添加新元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想采用现有的枚举并向其添加更多元素,如下所示:

I want to take an existing enum and add more elements to it as follows:

enum A {a,b,c}

enum B extends A {d}

/*B is {a,b,c,d}*/

这在 Java 中可行吗?

Is this possible in Java?

推荐答案

不,您不能在 Java 中执行此操作.除此之外,d 大概是 A 的一个实例(考虑到扩展"的正常想法),但用户只知道 A 不会知道它 - 这违背了枚举作为一组众所周知的值的意义.

No, you can't do this in Java. Aside from anything else, d would then presumably be an instance of A (given the normal idea of "extends"), but users who only knew about A wouldn't know about it - which defeats the point of an enum being a well-known set of values.

如果您能告诉我们更多关于您希望如何使用的信息,我们可能会建议替代解决方案.

If you could tell us more about how you want to use this, we could potentially suggest alternative solutions.

这篇关于枚举可以被子类化以添加新元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆