枚举属性&副作用 [英] enum properties & side effects

查看:100
本文介绍了枚举属性&副作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于枚举的问题(这可能是一个简单的但是....)。
这是我的程序:

  public class Hello {
public enum MyEnum
{
ONE(1),TWO(2);
private int value;
private MyEnum(int value)
{
System.out.println(hello);
this.value = value;
}
public int getValue()
{
返回值;
}
}
public static void main(String [] args)
{
MyEnum e = MyEnum.ONE;
}
}

我的问题是:为什么输出是



  hello 
hello

而不是



hello



代码如何去两次到构造函数?
什么时候是第一次,什么时候是第二次?
为什么枚举构造函数不能公开?
这是为什么打印两次而不是一次的原因?

解决方案

枚举是单身人士,他们是instanciated在加载课程时,所以两个hello来自于实施 MyEnum.ONE MyEnum.TWO 只需尝试打印的值



这也是为什么不能公开const的原因:枚举保证每个值只有一个实例 - 如果别人可以搞定构造函数,那么它就不能。


I have a question regarding enum (it might be a simple one but ....). This is my program:

public class Hello { 
         public enum MyEnum 
         { 
               ONE(1), TWO(2); 
               private int value; 
               private MyEnum(int value) 
               { 
                    System.out.println("hello");  
                    this.value = value; 
               } 
               public int getValue() 
               { 
                    return value; 
               } 
        } 
        public static void main(String[] args)  
        { 
              MyEnum e = MyEnum.ONE; 
        } 
}

and my question is: Why the output is

hello
hello

and not

hello ?

How the code is "going" twice to the constructor ? When is the first time and when is the second ? And why the enum constructor can not be public ? Is it the reason why it print twice and not one time only ?

解决方案

Enums are Singletons and they are instanciated upon loading of the class - so the two "hello"s come from instanciating MyEnum.ONE and MyEnum.TWO (just try printing value as well).

This is also the reason why the constuctor must not be public: the Enum guarantees there will ever only be one instance of each value - which it can't if someone else could fiddle with the constructor.

这篇关于枚举属性&副作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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