Java:如何在枚举中使用构造函数重载? [英] Java: How can one put to use constructor overloading in enums?

查看:811
本文介绍了Java:如何在枚举中使用构造函数重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Java中的枚举。我可以看到,有可能重载枚举构造函数。我的问题是,有可能在这个上下文中受益于构造函数重载,因为据我所知,它可能既不能自己调用​​它,也不能强制编译器调用你想调用的一个特定的。 p>

感谢您向我澄清这些内容的时间,希望对于可能有同样问题的其他人也有用。

解决方案

您可以在设置枚举值时调用它。例如:

  public enum Person 
{
FRED(Frederick,Fred
PETE(Peter,Pete),
MALCOLM(Malcolm); //没有昵称

private final String nickname;
private final String name;

private Person(String name,String nickname)
{
this.name = name;
this.nickname = nickname;
}

private Person(String name)
{
this(name,name); //只需使用名称作为昵称
}

// getNickname和getName
}

我已经在过去的各种项目中使用了这种能力。枚举是Java的最好的功能之一 - 当然是在C#中工作时,我想念的少数事情之一。 (他们可以更整洁地实施,我敢肯定,但...)


I am working with enumerations in Java. As I can see, it is possible to overload an enumeration constructor. My question is it possible at all to benefit from constructor overloading in this context given that as far as I understand it is possible neither to call it by yourself no to force the compiler to call a particular one that you would like to call?

Appreciate the time your take to clarify that stuff to me and hope it would also be useful for others who might have the same question in mind.

解决方案

You do call it - when setting the enum values. For example:

public enum Person
{
    FRED("Frederick", "Fred"),
    PETE("Peter", "Pete"),
    MALCOLM("Malcolm"); // No nickname

    private final String nickname;
    private final String name;

    private Person(String name, String nickname)
    {
        this.name = name;
        this.nickname = nickname;
    }

    private Person(String name)
    {
        this(name, name); // Just use the name as the nickname too
    }

    // getNickname and getName
}

I've used this ability for various projects in the past. Enums are one of Java's nicest features - certainly one of the few things I miss from Java when working in C#. (They could be implemented even more neatly, I'm sure, but...)

这篇关于Java:如何在枚举中使用构造函数重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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