Enum Constructors and Methods Tutorial

An enumeration, or enum for short, is a special data type that consists of a list of named constants. Each named constant is in fact a special class. Each named constant can have a constructor, instance variables, and methods. Let's start off slow with a simple enum declaration:
enum Sizes {
     SMALL, MEDIUM, LARGE;
}


Now let's add a private instance variable that will correspond to an int value representing the ounces of a hamburger patty.
enum Sizes {
     SMALL, MEDIUM, LARGE;
     private int ounces;
}


Starting to look like a special class declaration now. Let's add a constructor.
enum Sizes {
     SMALL, MEDIUM, LARGE;
     private int ounces;
     Sizes(int ounces){
         this.ounces = ounces;
    }
}


Okay, let's invoke that constructor and assign the instance variable a value for each enum value.
enum Sizes {
     SMALL(4), MEDIUM(8), LARGE(12);
     private int ounces;
     Sizes(int ounces){
         this.ounces = ounces;
    }
}


Finally let's create a getter method so we can do something with our private instance variable.
enum Sizes {
     SMALL(4), MEDIUM(8), LARGE(12);
     private int ounces;
     Sizes(int ounces){
         this.ounces = ounces;
    }
     int getOunces() {
         return ounces;
    }
}




Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md EnumConstructors
C:\Java>cd EnumConstructors
C:\Java\EnumConstructors>Notepad EnumConstructors.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


enum Sizes {
    SMALL(4), MEDIUM(8), LARGE(12);

    private int ounces;

    Sizes(int ounces){
        this.ounces = ounces;
    }

    int getOunces() {
        return ounces;
    }
} 

class EnumConstructors {
    public static void main(String args[]) {
        Sizes sRef = Sizes.MEDIUM;
        System.out.println(sRef.name());
        System.out.println(sRef.getOunces() + " ounce hamburger patty.");
        System.out.println();

        Sizes sArray[] = Sizes.values();
        for(Sizes s : sArray){
            System.out.println(s.name());
            System.out.println(s.getOunces() + " ounce hamburger patty.");
        }
    }
}

Now switch back to the command prompt (CMD) and type in javac EnumConstructors.java and press Enter.
Now type in java EnumConstructors and press Enter.


C:\Java\EnumConstructors>javac EnumConstructors.java
C:\Java\EnumConstructors>java EnumConstructors
MEDIUM
8 ounce hamburger patty.

SMALL
4 ounce hamburger patty.
MEDIUM
8 ounce hamburger patty.
LARGE
12 ounce hamburger patty.


Final thoughts


Tutorials