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"
.
In Java, enums are not simple aliases for integers, like in many other programming languages. In Java, enum values are full-blown objects which can have user-defined data, methods, etc.
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
. The Java compiler makes sure that there never will be more PetType
instances, and that CAT
and GOLDFISH
always refer to the same object.
But other than that MyEnum
is a normal class. 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. If you compile your code, you will see a file of the form Type$1.class
, which is this subclass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With