Marco V
Marco V

Reputation: 2653

When does Java enum method override following method?

I decided to get into more JAVA and I noticed in OCA 7 that an enum can declare a method which overrides another method. See this enum:

enum CoffeeSize {
    BIG(),
    HUGE(),
    OVERWHELMING() {
        public String getLidCode() {  // This method overrides the following method with similar name.
            return 'A';
        }
    }; // <--- is this semicolon I should be looking for?

    CoffeeSize(ounces) {
        this.ounces = ounces;
    }

    private int ounces;

    public int getOunces() {
        return ounces;
    }

    public String getLidCode() {
        return 'B';
    }
}

My question is in which case does a method in a enum override another method. Is it the method preceding the semicolon that overrides or what's the rule here?

Thanks for your time.

Upvotes: 1

Views: 151

Answers (1)

Jorn Vernee
Jorn Vernee

Reputation: 33885

The constants act similar to anonymous classes, where the enum itself is the abstract base class:

abstract class CoffeeSize {
    CoffeeSize(int ounces) {
        this.ounces = ounces;
    }

    private int ounces;

    public int getOunces() {
        return ounces;
    }

    public String getLidCode() {
        return "B";
    }
}

CoffeeSize OVERWHELMING = new CoffeeSize(3) {
    @Override
    public String getLidCode() {
        return "A";
    }
};

You can override the base implementation with any constant, not just the one before the semicolon:

enum CoffeeSize {
    BIG(1){
        @Override
        public String getLidCode() {
            return "C";
        }
    },
    HUGE(2) {
        @Override
        public String getLidCode() {
            return "B";
        }
    },
    OVERWHELMING(3) {
        @Override
        public String getLidCode() {
            return "A";
        }
    };
    ...
}

In the above, all the constants override getLidCode with a different implementation. The semicolon just marks the end of the list of constants.

Upvotes: 4

Related Questions