[英]Why does Java allow code blocks for enum constants?
I was typing an enum of Pokemon types when suddenly 我突然间输入了口袋妖怪类型的枚举
public enum Type {
NORMAL () { // This is the question. Why does Java allow this?
int x = 10; // Only accepts variables?
};
Type () {}
}
This code compiled correctly. 此代码编译正确。
What's the use of a code block for constants? 代码块对常量有什么用?
Code blocks in enums allows you to override methods defined in the enum type. 枚举中的代码块允许您覆盖枚举类型中定义的方法。 For instance
例如
enum Foo {
PEAR,
BANANA() {
@Override
public void doFoo() {
System.out.println("Banana foo");
}
},
APPLE,
GRAPE;
public void doFoo() {
System.out.println("Default foo");
}
}
Here Foo.BANANA.doFoo()
would produce "Banana foo"
, while calling doFoo()
on any other Foo
would produce "Default foo"
. 这里
Foo.BANANA.doFoo()
会产生"Banana foo"
,而在任何其他Foo
上调用doFoo()
会产生"Default foo"
。
In Java, enums are not simple aliases for integers, like in many other programming languages. 在Java中,枚举不是整数的简单别名,就像在许多其他编程语言中一样。 In Java, enum values are full-blown objects which can have user-defined data, methods, etc.
在Java中,枚举值是完整的对象,可以包含用户定义的数据,方法等。
If you write an enum class as follows: 如果你写一个枚举类如下:
enum PetType { CAT, GOLDFISH }
what actually happens is that you define a class PetType
(which is a subclass of the standard Java class Enum
) and two instances of this class, CAT
and GOLDFISH
. 实际发生的是你定义了一个
PetType
类(它是标准Java类Enum
的子类)和这个类的两个实例, CAT
和GOLDFISH
。 The Java compiler makes sure that there never will be more PetType
instances, and that CAT
and GOLDFISH
always refer to the same object. Java编译器确保永远不会有更多的
PetType
实例,并且CAT
和GOLDFISH
总是引用同一个对象。
But other than that MyEnum
is a normal class. 但
MyEnum
, MyEnum
是一个普通的课程。 You can define member variables and methods for it, which you can initialize through a constructor: 您可以为它定义成员变量和方法,您可以通过构造函数初始化它们:
enum PetType {
CAT(true),
GOLDFISH(false);
private boolean isHairy;
PetType(boolean isHairy) {
this.isHairy = isHairy;
}
public boolean isHairy() {
return isHairy;
}
}
This you can use in your own code: 这可以在你自己的代码中使用:
public static void displayWhetherHairy(CatType catType) {
if (catType.isHairy()) {
System.out.println("This pet is hairy!");
}
else {
System.out.println("This pet is not hairy!");
}
}
This is why you can use code in an enum definition. 这就是您可以在枚举定义中使用代码的原因。
What you do in your code is basically define another (anonymous) subclass of the Type
class, which defines an additional member variable x
with value 10. The only instance of this subclass is the NORMAL
object. 你在你的代码做的基本上是定义的另一个(匿名)子
Type
类,它定义了一个额外的成员变量x
与值10这个子类的唯一实例是NORMAL
对象。 If you compile your code, you will see a file of the form Type$1.class
, which is this subclass. 如果编译代码,您将看到一个
Type$1.class
的文件,它是这个子类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.