Can an enum have abstract methods? If so, what is the use, and give a scenario which will illustrate this usage.
lukastymo
Yes, but you may prefer enum which implements an interface, Look here. I think It looks much better. This is example for abstract method:
public enum Animal {
CAT {
public String makeNoise() { return "MEOW!"; }
},
DOG {
public String makeNoise() { return "WOOF!"; }
};
public abstract String makeNoise();
}
Yes, you can define abstract
methods in an enum
declaration if and only if all enum values have custom class bodies with implementations of those methods (i.e. no concrete enum value may be lacking an implementation).
public enum Foo {
BAR {
public void frobnicate() {
// do BAR stuff
}
},
BAZ {
public void frobnicate() {
// do BAZ stuff
}
};
public abstract void frobnicate();
}
来源:https://stackoverflow.com/questions/7413872/can-an-enum-have-abstract-methods