CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Packages

Packages
Enumerations
Enhance

Three methods of an enumeration constant

Method Description
name() Returns a String for the enumeration constant's name.
ordinal() Returns an int value that corresponds to the enumeration constant's position.
values() Returns the values that corresponds to the enumeration constant's list.

How to add a method to an enumeration

An enumeration that overrides the toString method
public enum ShippingType
{
    UPS_NEXT_DAY,
    UPS_SECOND_DAY,
    UPS_GROUND;

    public String toString()
    {
        String s = "";
        if (this.ordinal() == 0)
            s = "UPS Next Day (1 business day)";
        else if (this.ordinal() == 1)
            s = "UPS Second Day (2 business days)";
        else if (this.ordinal() == 2)
            s = "UPS Ground (5 to 7 business days)";
        return s;
    }
}
Code that uses the toString method
ShippingType ground = ShippingType.UPS_GROUND;
System.out.println("toString: " + ground.toString() + "\n");

Resulting output

toString: UPS Ground (5 to 7 business days)
Previous | Declare | Use | Enhance | Work with static imports | Application