Given the following enum:
enum Repeat {
Daily,
Weekly,
Yearly
}
I realize we are able to write it this way:
Repeat repeat = Repeat.Daily.Weekly.Yearly.Weekly;
which is equivalent to:
Repeat repeat = Repeat.Weekly;
May I know why such syntax is allowed? Is there a way to let the compiler warn us against this?
The main objective of enum is to define our own data types(Enumerated Data Types). Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.
yes, but you need to know that.
Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.
You cannot have an enum extend another enum , and you cannot "add" values to an existing enum through inheritance.
This is allowed as Daily, Weekly, Yearly
are the static
field by default
inside the enum
and holds the object of Repeat
. Also, you will get a warning from the compiler "The static field Repeat.Weekly should be accessed in a static way"
. It is similar to below lines of code.
class Foo{
public static Foo obj1 = new Foo();
public static Foo obj2 = new Foo();
public static Foo obj3 = new Foo();
}
Foo f = Foo.obj1.obj2.obj3; // will work fine but you will get a warning from the compiler.
Here is some part of bytecode inspection of Repeat
enum and from this, it is clear that Enum
variable is static
and holds the Object of Enum itself.
0: new #1 // class com/java8/demo/Repeat
3: dup
4: ldc #14 // String Daily
6: iconst_0
7: invokespecial #15 // Method "<init>":(Ljava/lang/String;I)V
10: putstatic #19 // Field Daily:Lcom/java8/demo/Repeat;
13: new #1 // class com/java8/demo/Repeat
Enum instance are just static
instance of the enum class.
We have two way to access static field of a class:
When you chain your enum:
Repeat repeat = Repeat.Daily.Weekly.Yearly.Weekly;
It's just like get a static field from an instance of a class.
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