对枚举进行子类化 [英] Subclassing an enum

查看:142
本文介绍了对枚举进行子类化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以继承Java enum

is there a simple way to subclass a Java enum?

我问这个因为我喜欢10他们实现相同的接口,但他们也有一些方法相同的实现,所以我想通过将所有相同的实现放在扩展枚举的中间对象中来重用代码它也是我需要的所有其他人的超类。

I ask this because I have like 10 of them that implement the same interface but they also have the same implementation for some methods so I would like to reuse the code by placing all the same implementations in middle object that extends Enum and it is also the superclass of all the others I need.

也许它不像我想的那么简单?

Maybe it is not so straightforward as I think?

提前感谢

推荐答案

你不能这样做,因为语言不允许你。并且出于一个很好的逻辑原因:如果你能够从子类中删除某些枚举值,而不是添加新的枚举值,那么继承枚举只会有意义。否则你将破坏 Liskov替代原则

You can't do it, since the language does not allow you. And for a good logical reason: subclassing an enum would only make sense if you could remove some enum values from the subclass, not add new ones. Otherwise you would break the Liskov Substitution Principle.

这简要说明每当预期超类的实例时,子类的每个实例都应该是可接受的。如果在枚举子类中添加新的枚举成员,那么只知道超级枚举的人就不能接受。

This in brief states that every instance of a subclass should be acceptable whenever an instance of a superclass is expected. If you add a new enum member in an enum subclass, that clearly can't be accepted by someone knowing only the super enum.

有关更多详细信息和可能的替代方案,请参阅我之前的这个答案

For more details and possible alternatives, see this earlier answer of mine.

在你的具体案例中,@ Jason的建议可能会提供一个很好的解决方案(+1为他: - )

In your concrete case, @Jason's suggestion may offer a good solution (+1 for him :-)

好点,我上面有点草率:-)实施方面你是对的。但是,从逻辑的角度来看,枚举类型由其有效值集完全描述。通常,适当的子类是其超类的特化。换句话说,有效子类实例的集合(应该)始终是超类实例集的子集(每只狗都是动物,但不是每只动物都是狗。)

Good point, I was a bit sloppy above :-) Implementation-wise you are right. However, from the logical point of view an enum type is fully described by the set of its valid values. And generally, a proper subclass is a specialization of its superclass. In other words, the set of valid subclass instances is (should be) always a subset of the superclass instance set. (Every dog is an animal, but not every animal is a dog.)

这篇关于对枚举进行子类化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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