Reputation: 47
Problem : I need to perform different actions or executing different line of codes (which can be done by calling different methods) based on different Enum values and don't want to use if else.
Suppose I have following enum :
public enum Sports
{
FOOTBALL, HOCKEY;
}
Can we use Sports.FOOTBALL and Sports.HOCKEY to call different methods with same name (method overloading) or even different methods with different name ?
public void method(parameter(s)) //call this method when Enum is Sports.FOOTBALL
{
}
public void method(parameter(s)) //call this method when Enum is Sports.HOCKEY
{
}
Both methods are part of the same class. I am looking solution for any of the case (when method have same name or different name).
Upvotes: 1
Views: 1322
Reputation: 140427
Method signatures need different types so that the compiler can distinguish them.
But: the type of your enum is Sports
. Sports.Football
or Sports.Hockey
are just instances of that type; more or less like "1" and "2" are instances of the String type.
Thus: no overloading possible for different enum constants.
The "best" you can achieve would be to switch()
over your enum instance, and then "dispatch" accordingly, or as mentioned in the comments: a Map that can map
your different enum constants to some sort of "executable code block".
Upvotes: 5