Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum with no instances

In RXJava [1] there is an enum [2] defined as

public enum JavaFxObservable {
    ; // no instances


    public static void staticMethod() {
        // ...
    }
}

What's the purpose this technique using a enum with no instances? Why not use a standard class?


  • [1] https://github.com/ReactiveX/RxJava
  • [2] https://github.com/ReactiveX/RxJavaFX/blob/0.x/src/main/java/rx/observables/JavaFxObservable.java
like image 888
lukstei Avatar asked Sep 30 '14 10:09

lukstei


People also ask

Is Java enum static?

The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).

Can enum have static methods Java?

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.

What are enumerations Java?

Enumeration means a list of named constant. In Java, enumeration defines a class type. An Enumeration can have constructors, methods and instance variables. It is created using enum keyword. Each enumeration constant is public, static and final by default.

Can enums have constructors?

Enum in Java contains fixed constant values. So, there is no reason in having a public or protected constructor as you cannot create an enum instance. Also, note that the internally enum is converted to class. As we can't create enum objects explicitly, hence we can't call the enum constructor directly.


1 Answers

What's the purpose this technique using a enum with no instances?

You are defining, in the simplest way, that this is a class which has no instances, i.e. it is utility class.

Why not use a standard class?

An enum is a class. It is also final with a private constructor. You could write

public final class JavaFxObservable {
    private JavaFxObservable() {
        throw new Error("Cannot create an instance of JavaFxObservable");
    }
}

But this is more verbose and error prone. e.g. I have seen this in real code

public final class Util {
    private Util() {
    }

    static void someMethod() { }

    static class DoesSomething {
         void method() {
             // WAT!? we can still create this utility class
             // when we wrote more code, but it's not as good.
             new Util().someMethod(); 
         }
    }
}

The comments are mine. ;)

like image 190
Peter Lawrey Avatar answered Oct 17 '22 00:10

Peter Lawrey