Accessing Single Enum Values in Java via Custom Accessor Methods

alpharithms fallback 1

Enums are powerful data structures with named constants that can serve as valuable tools in a range of programming designs. They are often used to maintain a centralized collection of default values.

As enum definitions grow more complex, the means of conveniently accessing more complex data requires greater levels of effort. Enums also called enumeration or, in the case of Ruby, factor, are a common datatype provided by most modern programming languages.

Python, being a notable exception, still provides a functional equivalent via its dictionary datatype. Given, implementation is quite different. To illustrate the functionality of enums common to C++, C#, and Java, the following examples demonstrate how to access enum values explicitly via custom accessor methods.

Basic Enum Example

The following code creates a new Enum class named Letter which defines a collection of alphabetical letters (A-E) as the set of named values. In this instance, Letter defines its values as a tuple consisting of two values: a single char and a single int. These represent the character value associated with a letter and its numerical position in the [English] alphabet.

enum Letter{

    // Define enum values
    A('a', 1),
    B('b', 2),
    C('c', 3),
    D('d', 4),
    E('e', 4);

    // Declare values
    char letter;
    int position;

    // Default constructor
    Letter(char letter, int position) {
        this.letter = letter;
        this.position = position;
    }
}

This is a fine start but doesn’t address possible use cases where convenient access to the positional values would be needed. For example, the following code illustrates a minimal implementation of an instance of the Letter enum:

public static void main(String[] args) {
    
    // Create an instance of Letter
    Letter myLetter = Letter.A;

    // Print the new instance's default representation
    System.out.println(myLetter);    

}

// Resulting Output
A

Note that the resulting output to standard out is the String representation of the named constant—not the defined char representation. In other words, if the named value of A were instead AYE the resulting output would have been AYE. This behavior is expected and defined in the official Java Enum documentation.

Custom Accessor Methods

Enums provide methods by which one can iterate through values but no standard means by which to access named values data. In the code below, the Letter enum has been expanded to provide convenient access to both the letter and position values of a Letter instance.

enum Letter{

    // Define enum values
    A('a', 1),
    B('b', 2),
    C('c', 3),
    D('d', 4),
    E('e', 4);

    // Declare values
    char letter;
    int position;

    // Default constructor
    Letter(char letter, int position) {
        this.letter = letter;
        this.position = position;
    }

    // Accessor method for letter
    public char getLetter(){
        return this.letter;
    }

    // Accessor method for position
    public int getPosition(){
        return this.position;
    }
}

In this example code, the accessor methods getLetter and getPosition allow direct access to the named values tuples. This allows one to access both the char representation and int position value as letterInstance.getLetter() or letterInstance.getPosition(). To better illustrate this, the following example code iterates through all values in the Letter enum printing the position and character value.

public static void main(String[] args) {

    // Iterates through all Letter values (A-E)
    for (Letter l: Letter.values()) {

        // Output each letter and position value as a formatted string.
        System.out.println(
                MessageFormat.format(
                        "Letter: {0}, Positions: {1}",
                        l.getLetter(), l.getPosition()));
    }
}

// Resulting output
Letter: a, Positions: 1
Letter: b, Positions: 2
Letter: c, Positions: 3
Letter: d, Positions: 4
Letter: e, Positions: 4

At first glance, I felt the lack of standardized access to enum values was a massive downside to the data structure. However, I quickly realized the requirement of custom implementation provided enums a much more dynamic range of applications. Requiring custom accessor methods to named values opens up enums for a wider (if not endless) range of possible data representations.

Final Thoughts

Enumerated values (enums) were not always standard parts of programming languages. Before their conception, constants were often assigned default values (a.k.a. magic numbers). Enums were a solution to provide a more self-documenting means to incorporate constants and standardized values into large-scale software.

The examples of Java enums here illustrate a basic definition of an enum class that leverages the power of custom accessor methods. While simple in concept, this approach provides endless means for developers to conveniently access the values of an Enum.

Zαck West
Full-Stack Software Engineer with 10+ years of experience. Expertise in developing distributed systems, implementing object-oriented models with a focus on semantic clarity, driving development with TDD, enhancing interfaces through thoughtful visual design, and developing deep learning agents.