What is the best approach for using an Enum as a singleton in Java?

Miles D picture Miles D · Jan 9, 2009 · Viewed 76.4k times · Source

Building on what has been written in SO question Best Singleton Implementation In Java - namely about using an enum to create a singleton - what are the differences/pros/cons between (constructor omitted)

public enum Elvis {
    INSTANCE;
    private int age;

    public int getAge() {
        return age;
    }
}

and then calling Elvis.INSTANCE.getAge()

and

public enum Elvis {
    INSTANCE;
    private int age;

    public static int getAge() {
        return INSTANCE.age;
    }
}

and then calling Elvis.getAge()

Answer

Jon Skeet picture Jon Skeet · Jan 9, 2009

Suppose you're binding to something which will use the properties of any object it's given - you can pass Elvis.INSTANCE very easily, but you can't pass Elvis.class and expect it to find the property (unless it's deliberately coded to find static properties of classes).

Basically you only use the singleton pattern when you want an instance. If static methods work okay for you, then just use those and don't bother with the enum.