Search code examples
javaenumsrx-javarx-javafx

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?



Solution

  • 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. ;)