Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an empty Java enum type with methods?

Tags:

java

enums

I can create an empty Java enum type, but when i want to add some methods : i get a "syntax error" (into Eclipse). I found no official documentation about this, so my question is : is it just impossible (so where is it clearly mentioned?) or is it just the compiler which is wrong ?

like image 993
cedric Avatar asked Sep 06 '11 09:09

cedric


People also ask

Can a Java enum be empty?

An ENUM can also contain NULL and empty values. If the ENUM column is declared to permit NULL values, NULL becomes a valid value, as well as the default value (see below).

Can Java enum 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.

Can we write method inside enum?

An enum class can include methods and fields just like regular classes. When we create an enum class, the compiler will create instances (objects) of each enum constants. Also, all enum constant is always public static final by default.

How do you add an empty string to an enum in Java?

setCode (Main. Code. EMPTY); your variable 'code' of the 'Main' instance would be an empty string.


1 Answers

Yes it's possible. You just need to add a ; to terminate the (empty) list of enum constants:

enum TestEnum {
    ;                         // doesn't compile without this.
    public void hello() {
        System.out.println("Hello World");
    }
}

JLS Syntax Definition for enums

(Note that without any instances, you'll only be able to call the static methods of the Enum.)

Related:

  • Zero instance enum vs private constructors for preventing instantiation
like image 155
aioobe Avatar answered Oct 21 '22 13:10

aioobe