Java enumeration without instances

RXJava [1] has an enumeration [2] defined as

public enum JavaFxObservable { ; // no instances public static void staticMethod() { // ... } } 

What is the purpose of this technique using non-instance enumeration? Why not use a standard class?


+6
source share
1 answer

What is the purpose of this technique using non-instance enumeration?

You define in the simplest way that this is a class that has no instances, i.e. This is a utility class.

Why not use a standard class?

An enum is a class. It is also final with the help of a private constructor. You can write

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

But it is more verbose and error prone. for example I saw 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 not as good. new Util().someMethod(); } } } 

My comments;)

+5
source

Source: https://habr.com/ru/post/976047/


All Articles