Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java allow code blocks for enum constants?

Tags:

java

enums

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?

like image 650
vixrant Avatar asked Dec 14 '22 18:12

vixrant


2 Answers

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".

like image 108
khelwood Avatar answered Dec 17 '22 08:12

khelwood


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.

like image 25
Hoopje Avatar answered Dec 17 '22 09:12

Hoopje