Regarding enums in java how I understood is
Sample enum
public enum Strategy {
STRATEGY_A {
@Override
void execute(){
System.out.print("Executing strategy A");
}
},
STRATEGY_B {
@Override
void execute(){
System.out.print("Executing strategy B");
}
};
abstract void execute();
}
This would be compiled to something like
public abstract class Strategy extends java.lang.Enum<Strategy> {
public static final Strategy STRATEGY_A;
public static final Strategy STRATEGY_B;
private static final Strategy[] $VALUES;
public static Strategy[] values();
public static Strategy valueOf(java.lang.String);
private Strategy();
abstract void execute();
Strategy(java.lang.String, int, Strategy$1);
static {};
}
and the enum STRATEGY_A would be like a sub class which extends its base class STRATEGY
final class Strategy$1 extends Strategy {
Strategy$1(java.lang.String, int);
void execute();
}
I could get the above with the help of javap by reading the class file.
As far as I understand, enum fields (or) constants are nothing but class objects of enum. For example
public enum Fruits {
APPLE; //APPLE would be the instance of Fruits
ORANGE; //ORANGE would be the instance of Fruits
GRAPES; //GRAPES would be the instance of Fruits
}
But why does the enum filed STRATEGY_A and STRATEGY_B extend the base class or base enum STRATEGY? I couldn't differentiate between "enum fields (APPLE, ORANGE)" and "enum sub classes (STRATEGY_A, STRATEGY_B)" like the above. What do they really mean by each other?
EDIT
All these doubts came while implementing strategy pattern with enum.
Best Answer
How would you have written the enum class as if the
enum
structure had not been added in Java? You would implement it like this:When you compile this class, it will also generate new classes (following is from
javap
):Essentially this is the same as what you got for the enum:
Would it look better if you view them as anonymous classes?
Now, why do non-overridden classes do not have implementations? This is because there are no anonymous classes needed.
Similarly, for enums that only have some fields overriding the value, only those fields will have subclasses. See this Foo.java file:
It is compiled into:
This is similar to the output of this class:
So in the end, your question doesn't stand -- there is no need to differentiate subclasses or not, because they just behave like anonymous classes. If you understand subclassing well enough, you would understand that there is no difference between subclass or not if you use it properly (which includes not using reflections).