在Java中扩展枚举 [英] Extending a enum in Java

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

问题描述

我有一个枚举,我们称之为A:

  public enum A 
{
A ,
B
}

我有一个使用枚举的功能A:

  public void functionA(A enumA)
{
// do something
}

如何创建另一个枚举,可能会调用B,我可以传递给 functionA ?这样的东西?

  public enum B 
{
C
}

functionA(BC);

我知道您不能扩展枚举,但还有其他选项可用吗?

解决方案

你不能。


$ b $枚举类型是最终的设计。



原因是每个枚举类型应该只有在枚举中声明的元素因为我们可以在switch语句中使用它们),如果允许扩展类型,这是不可能的。



你可能会这样做: p>

  public interface MyInterface {
//添加所需的所有方法
}

public enum A implements MyInterface {
A,B;
//实现MyInterface的方法
}

public enum B实现MyInterface {
C;
//实现MyInterface的方法
}

请注意,它不是然后可以使用这个界面执行开关。 (或者一般有一个开关,其中一个对象可能来自多个枚举)。


I have an enum, let's call it A:

public enum A
{
    A,
    B
}

I have a function that takes an enum A:

public void functionA(A enumA)
{
    //do something
}

How can I create another enum, possibly call B that I can pass to functionA? Something like this?

public enum B
{
    C
}

functionA(B.C);

I know that you can't extend an enum, but what other options do I have available? What is the best way to achieve this?

解决方案

You can't.

Enum types are final by design.

The reason is that each enum type should have only the elements declared in the enum (as we can use them in a switch statement, for example), and this is not possible if you allow extending the type.

You might do something like this:

public interface MyInterface {
    // add all methods needed here
}

public enum A implements MyInterface {
    A, B;
    // implement the methods of MyInterface
}

public enum B implements MyInterface {
    C;
    // implement the methods of MyInterface
}

Note that it is not possible to do a switch with this interface, then. (Or in general have a switch with an object which could come from more than one enum).

这篇关于在Java中扩展枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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