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?
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).
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.
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.
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.
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. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With