public enum myEnum {
VAL1(10), VAL2(20), VAL3("hai") {
public Object getValue() {
return this.strVal;
}
public String showMsg() {
return "This is your msg!";
}
};
String strVal;
Integer intVal;
public Object getValue() {
return this.intVal;
}
private myEnum(int i) {
this.intVal = new Integer(i);
}
private myEnum(String str) {
this.strVal = str;
}
}
In the above enum what exactly happens when I add a constant specific class body for VAL3?
The type of VAL3 is definetly a subtype of myEnum as it has overloaded and additional methods. (the class type comes as 'myEnum$1' )
But how can the compiler creates a subtype enum extending myEnum as all the enums are already extending java.lang.enum ?
VAL3.showMsg()won't be visible outside ofVAL3. Only methods that are declared in the enum type can be used outside, linkemyEnum.getValue(). This means, there is no point in declaring individual public methods that were not defined before in the enum type. Of course, you can define arbitrary helper methods in each enum value, but you should keep in mind that they are not accessible from outside. Make helper methods private to make this clear to the reader of your code.