I’m writing an abstract class in Java where I’d like a parameter of one of my abstract methods to be an enum, so I’ve got the following. Note that only subclasses will know what possible states it can have. (Please excuse the contrived example)
public abstract class StateTracker {
public abstract boolean isInState(???????? state);
}
What is ????????? Therein lies the problem:
- Ideally it would be an abstract enum called StateEnum that has no instances, and the clients of StateTracker could make their own concrete StateEnums. But we can’t do anything like that in Java.
- I could make it an interface, but then I’d have no way of ensuring that the subclasses implement it as an enum, which is the goal.
-
I could change it to Enum < ? >. So I try that, and in my subclass I do something like this:
public class MyStateTracker extends StateTracker { public enum MyState { BADSTATE_1, BADSTATE_2 } @Override public boolean isInState(?!?!?!?! state) { // TODO Auto-generated method stub return false; } }
Now what is ?!?!?!?! Here are the possibilities:
- MyState. This doesn’t compile since it doesn’t think that I’m overriding the abstract method.
- Enum. Same problem.
How can I ensure that concrete classes use an emum?
It depends on whether you want to be able to ask a
StateTrackerwhether it is in states declared by differentenumtypes.If you want to lock down the states so that a given state tracker can only be queried for one type of
enum, create a generic type:If you have a couple of
enumtypes defining states like this:… and you want to be able to ask a
StateTrackerwhether it is in any state (defined by anyenum, really, unless you also declare aStatemarker interface for yourenumto implement), then create a generic method: