Java枚举支持方法吗?但在c#中不行?
我正在查看在java中执行单例的正确方法的代码: 在 Java 中实现单例模式的有效方法是什么?
我有点困惑,如何向枚举添加方法?
public enum Elvis {
INSTANCE;
private final String[] favoriteSongs =
{ "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
}
上面代码中的枚举对我来说甚至没有意义,你有这个符号:
INSTANCE;
那怎么是正确的行呢?
我来自 c#,这种语法让我很好奇,我希望有人能够解释或理解上述内容。
我想这意味着java对枚举有更纯粹的想法,因为它可以有行为?
I'm looking at this code of the correct way to do a singleton in java: What is an efficient way to implement a singleton pattern in Java?
I'm a little confused, how do you add a method to a enumeration?
public enum Elvis {
INSTANCE;
private final String[] favoriteSongs =
{ "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
}
And the enumeration in the code above, doesn't even make sense to me, you have the symbol:
INSTANCE;
how is that a correct line?
I'm coming from c#, and this syntax got me curious and I'm hoping someone can explain or make sense of the above.
I guess it means java has a more purer idea of an enumeration as it can have behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用扩展方法
用法:
You could use an extension method
Usage:
给出一个稍微不同的答案,我认为您正在问这个问题,Java 代码中的
INSTANCE;
行与以下 C# 示例中的Instance
行等效:这是为 Java
enum
创建值
的方式。为了进一步说明这个例子,Java 枚举可以是:其中值类型是
Gender.MALE
和Gender.FEMALE
相当于:在 C# 中。
如果我偏离了你的问题,我深表歉意。
To give a slightly different answer, and one that I think you're asking, the
INSTANCE;
line in the Java code is the equivalent line ofInstance
in the following C# example:It's the way you create a
value
for a Javaenum
. To further the example a Java enum could be:Where the value types are
Gender.MALE
andGender.FEMALE
which is equivalent to:in C#.
If I have veered far from your question I apologize.
Java 中的枚举实际上是一个类。隐式扩展 java.lang.Enum 的一种。您在
INSTANCE;
中看到的特殊语法是枚举常量的声明。这将用于创建可以在代码中引用的枚举类的实例。事实上,您甚至可以为枚举设置一个非默认构造函数,并在常量声明中使用它。示例:将枚举视为真实对象具有某些优点。将一些逻辑放入枚举中很方便,但也不应该被滥用。不过,在我看来,通过枚举的单例模式是一个很好的解决方案。
An enum in Java is actually a class. One that implicitly extends java.lang.Enum. The special syntax you see at
INSTANCE;
is a declaration of an enum constant. This is going to be used to make an instance of your enum class which can be referred to in code. As a matter of fact, you can even have a non-default constructor for your enum and use it in the constant declaration. Example:Treating enums as true objects has certain advantages. Putting some logic into enums is convenient, but shouldn't be abused either. The singleton pattern via enums is a nice solution in my opinion, though.