Good day!
I have an interface which only implements one single method. I dont feel like making several class which all implement this one single method therefore I decided to use anonymous classes instead.
I use enums for certain static items, these enums have instances of my interface. However, when I try to make an anonymous class inside my enum constants my IDE (eclipse) literally tells me nothing (as if it is outside a code block).
My question is as follows: Can I use anonymous classes inside my enum constants?
If my text was unclear (Sorry im not english) please see the example below.
Code example
/**
* My Interface
*/
public interface IPotato {
public void eatPotato();
}
/**
* My enum class
*/
public enum PotatoEnum {
I_WANT_TO_EAT_POTATO(new IPotato() {
@Override
public void eatPotato() {
// Cant put code here.
} });
private IPotato _myAnonymousClass;
private PotatoEnum(IPotato anonymousClass){
this._myAnonymousClass = anonymousClass;
}
public IPotato getPotato(){
return _myAnonymousClass;
}
}
You could do that, it is a perfectly valid solution.
As a recommendation, make your enum implement your interface to make the code more readable:
public enum PotatoEnum implements IPotato{
I_WANT_TO_EAT_POTATO(){
@Override
public void eatPotato() {
// Cant put code here.
}},//more ENUMS ;
}
Simply yes
By doing this you are doing something like that:
I_WANT_TO_EAT_POTATO(An object of a virtual class that implments IPotato class);
same as :
I_WANT_TO_EAT_POTATO(Passing any parameter defined by constructor);
See Enum
constants as an Inner Classes and you are passing them parameters of their construcors
You can to that. The reason of your mistake is that you have two public identifier (enum and interface) in single file . remove public from enum and it will work
public interface IPotato {
public void eatPotato();
}
enum PotatoEnum {
I_WANT_TO_EAT_POTATO(new IPotato() {
@Override
public void eatPotato() {
// Cant put code here.
}
});
private IPotato _myAnonymousClass;
private PotatoEnum(IPotato anonymousClass) {
this._myAnonymousClass = anonymousClass;
}
public IPotato getPotato() {
return _myAnonymousClass;
}
}
来源:https://stackoverflow.com/questions/35156587/java-enums-anonymous-class-inside-enum-constant