Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enumerations support methods? But not in c#?

I'm looking at this code of the correct way to do a singleton in java: What is an efficient way to implement a singleton pattern in Java?

I'm a little confused, how do you add a method to a enumeration?

 public enum Elvis {
       INSTANCE;
       private final String[] favoriteSongs =
           { "Hound Dog", "Heartbreak Hotel" };
       public void printFavorites() {
           System.out.println(Arrays.toString(favoriteSongs));
       }
   }

And the enumeration in the code above, doesn't even make sense to me, you have the symbol:

INSTANCE;

how is that a correct line?

I'm coming from c#, and this syntax got me curious and I'm hoping someone can explain or make sense of the above.

I guess it means java has a more purer idea of an enumeration as it can have behaviour?

like image 430
codecompleting Avatar asked Oct 28 '11 21:10

codecompleting


People also ask

How Java enumeration is different from C and C++?

Enums in C/C++ are plain Integers. Enums in Java are objects - they can have methods (with different behavior from one enum instance to the other). Moreoever, the enum class supplies methods which allows iteration over all enum instances and lookup of an enum instance. Save this answer.

How are enumerations in Java superior to enumerations in C?

In C, an enumeration is just a set of named, integral constants. In Java, an enumeration is more like a named instance of a class. You have the ability to customize the members available on the enumeration.

Can enumerations have methods?

The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.


1 Answers

An enum in Java is actually a class. One that implicitly extends java.lang.Enum. The special syntax you see at INSTANCE; is a declaration of an enum constant. This is going to be used to make an instance of your enum class which can be referred to in code. As a matter of fact, you can even have a non-default constructor for your enum and use it in the constant declaration. Example:

public enum Test {

    INSTANCE("testing");

    private final String content;
    public Test(final String content) {
        super();
        this.content = content;
    }

}

Treating enums as true objects has certain advantages. Putting some logic into enums is convenient, but shouldn't be abused either. The singleton pattern via enums is a nice solution in my opinion, though.

like image 171
G_H Avatar answered Oct 13 '22 00:10

G_H