8

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?


tomrozb
  • 25,773
  • 31
  • 101
  • 122
lukstei
  • 844
  • 2
  • 8
  • 20
  • 1
    Not sure really, but i think it might be clean way to prevent from extending or creating instance – user902383 Sep 30 '14 at 10:56
  • This "class" is just a repository of static functions (and/or constants). An enum cannot be extended, is a final class. The alternative would be to make a final or abstract class with a private constructor. Which is more verbose. BTW enum is also used for a singleton, with concurrency safe initialisation. – Joop Eggen Sep 30 '14 at 10:58
  • "Why not use a standard class?" can you give an example of how such a standard class would be better/simpler? – Peter Lawrey Sep 30 '14 at 10:58
  • 1
    Saves you from writing a `private` constructor and marking the class `final`. e.g. This can be used to create helper classes which only contain static methods without being instantiable (And it also reduces the amount boilerplate code that you'd normally write) – Matt Sep 30 '14 at 10:58

1 Answers1

7

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

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130