Search code examples
javascjp

Enum Example Explanation


Here is a program taken from the SCJP 6 example. Here, we create a enum with different coffee sizes, and declare a private variable called ounces to get the ounce value part of enumeration.

I was not able to understand the use of getLidCode method which is overriden. How would one access the getLidCode method?

package com.chapter1.Declaration;

enum CoffeSize {
    BIG(8), HUGE(10), OVERWHELMING(20) {
        public String getLidCode() {
            return "B";
        }
    };

    CoffeSize(int ounce) {
        this.ounce = ounce;
    }

    private int ounce;

    public int getOunce() {
        return ounce;
    }

    public void setOunce(int ounce) {
        this.ounce = ounce;
    }

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

public class Prog7 {

    CoffeeSize size;

    public static void main(String[] args) {

        Prog7 p = new Prog7();
            p.size = CoffeeSize.OVERWHELMING;

            System.out.println(p.size.getOunces());

            //p.size.getLidCode(); ? is this correct way
        }
    }

Solution

  • It makes more sense if you space it out a bit more:

    enum CoffeSize {
        BIG(8),
        HUGE(10),
        OVERWHELMING(20) {
            public String getLidCode() {
                return "B";
            }
        };
        // rest of enum code here
    }
    

    Only OVERWHELMING is overriding getLidCode().

    You would access it via this approach (using your code):

    System.out.println(p.size.getLidCode());
    

    The reason for this: p.size is type CoffeSize, of which it has the method getLidCode(). It will print the value of the overridden method, as expected.