Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Enumeration or Class?

I implement a Singleton using the enum approach:

public enum Singleton {
    INSTANCE;

    public void doStuff(String stuff) {
        System.out.println("Doing " + stuff);
    }
}

How do I call it right (I don't mean execute, just how to write it)? Is it still a class or now an enumeration? I'm just interested in the theoretical part.
If talking about object orientation and classes, can I say I created a Singleton class of type enumeration?

Upvotes: 3

Views: 218

Answers (5)

Balaswamy Vaddeman
Balaswamy Vaddeman

Reputation: 8530

It is Enum and it is also a type of class since Java5.0.

You are creating Singleton with Enum.

learn more about Enum

Upvotes: 0

yshavit
yshavit

Reputation: 43391

An enum in Java is just a class (as you seem to know), so you should be fine calling it any of the above. It's a bit subjective, but I think it depends on which aspects of it you want to highlight.

  • if you want to highlight that it's this thing that can instantiate an object with state and methods, call it a class
  • if you want to highlight the object itself, call it the singleton instance
  • if you want to highlight that it's using the enum to implement the singleton pattern, call it an enum
  • if you want to highlight the fact that it's a singleton (without referring to how that pattern is implemented), call it a singleton
  • if you want to highlight the fact that it's a singleton pattern implemented via an enum, call it a singleton enum

I would understand any of those terms, and I wouldn't judge someone for using one vs another.

Upvotes: 3

ianpojman
ianpojman

Reputation: 1793

It's an enum. The java language ensures the INSTANCE enum value will be instantiated once (per classloader, so usually once per JVM) and the Singleton.INSTANCE field will let you access the single instance.

You could also just do:

public class Singleton {
    public static Singleton instance INSTANCE = new Singleton();

    private Singleton() { /* private ctor so people can't instantiate their own */ }
}

but the enum approach makes it cleaner (if you have JDK5 or up)

Upvotes: 0

Scorpion
Scorpion

Reputation: 3976

In this case, you have create a singleton object INSTANCE which is an enum (in this case INSTANCE). The jvm ensures that only one instance of an enum exists; thereby they can be viewed as singleton by default. You can find some more details here

Upvotes: 0

MByD
MByD

Reputation: 137362

It's an enum, and it's also a class. Enum is a type of class.

Upvotes: 2

Related Questions