Why does Java allow code blocks for enumeration constants?

I printed an enumeration 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 is correctly composed.

What is the use of a code block for constants?

+4
source share
2 answers

Code blocks in enumerations allow you to override the methods defined in an enumeration 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");
    }
}

It Foo.BANANA.doFoo()will create here "Banana foo", and a call doFoo()on any other Foowill result in "Default foo".

+10
source

Java - , . Java enum , , ..

:

enum PetType { CAT, GOLDFISH }

, , PetType ( Java Enum) , CAT GOLDFISH. Java , PetType CAT GOLDFISH .

MyEnum . - , :

enum PetType {
    CAT(true),
    GOLDFISH(false);

    private boolean isHairy;

    PetType(boolean isHairy) {
        this.isHairy = isHairy;
    }

    public boolean isHairy() {
        return isHairy;
    }
}

:

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!");
    }
}

.

, () Type, - x 10. NORMAL. , Type$1.class, .

+2

All Articles