Using methods and static blocks and Zero instance enum


Using methods and static blocks

An enum can contain a method, just like any class. To see how this works, we'll declare an enum like this:

public enum Color {
    RED, BLUE, GREEN, YELLOW;
}

Let's have a method that returns the enum in the opposite direction:

public enum Color {
    RED, BLUE, GREEN, YELLOW;
 
    public Color getComplementary() {
        switch (this) {
            case RED:
                return GREEN;
            case GREEN:
                return RED;
            case BLUE:
                return YELLOW;
            case YELLOW:
                return BLUE;
            default:
                return null;
        }
    }
}

Let's have a method that returns the enum in the opposite direction:

public enum Color {
    RED, BLUE, GREEN, YELLOW;
 
    private Color oppositeColor;
 
    public Color getOpposite() {
        return oppositeColor;
    }
 
    static {
        RED.oppositeColor = GREEN;
        GREEN.oppositeColor = RED;
        BLUE.oppositeColor = YELLOW;
        YELLOW.oppositeColor = BLUE;
    }
}

Zero instance enum

enum Util {
	/* No instances */;
	public static int clamp(int min, int max, int i) {
		return Math.min(Math.max(i, min), max);
	}
	// other utility methods...
}

Just as enum can be used for singletons (1 instance classes), it can be used for utility classes (0 instance classes). Just make sure to terminate the (empty) list of enum constants with a ;

See the question Zero instance enum vs private constructors for preventing instantiation for a discussion on pro's and con's compared to private constructors.


Enum as a bounded type parameter

When writing a class with generics in java, it is possible to ensure that the type parameter is an enum. Since all enums extend the Enum class, the following syntax may be used.

public class Holder<T extends Enum<T>> {
	public final T value;
	public Holder(T init) {
		this.value = init;
	}
}

In this example, the type T must be an enum.


Documenting enums

Not always the enum name is clear enough to be understood. To document an enum, use standard javadoc:

/**
 * United States coins
 */
public enum Coins {
 
	/**
	* One-cent coin, commonly known as a penny,
	* is a unit of currency equaling one-hundredth
	* of a United States dollar
	*/
	PENNY(1),
 
	/**
	* A nickel is a five-cent coin equaling
	* five-hundredth of a United States dollar
	*/ 
	NICKEL(5),
 
	/**
	* The dime is a ten-cent coin refers to
	* one tenth of a United States dollar
	*/ 
	DIME(10),
 
	/**
	* The quarter is a US coin worth 25 cents,
	* one-fourth of a United States dollar
	*/ 
	QUARTER(25);
 
	private int value;
 
	Coins(int value){
		this.value = value;
	}
 
	public int getValue(){
		return value;
	}
}

Basic Programs