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.
new Strategy(){}
like what you have mentioned... Sounds new to me... What does it mean? Do we override the class there? – Tom Taylor Mar 09 '17 at 09:53Now, why do non-overridden classes do not have implementations? This is because there are no anonymous classes needed.
What does it mean? I couldn't get you here.... – Tom Taylor Mar 09 '17 at 09:58If 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).
... I couldn't get you here :( – Tom Taylor Mar 09 '17 at 10:05new Object()
calls. For information on anonymous classes, there are many guides online :) – SOFe Mar 10 '17 at 11:42