Java enum inheritance: Is it possible to somehow extract the enums' toString() method to a common super class/enum?
I have 4 different classes with a common superlass called WebService
that each have the following enums declared in them (with different values):
public class GeoPlacesService extends WebService {
public enum RequestParam {
LOCATION, RADIUS, SENSOR, KEY;
@Override
public String toString() {
return super.toString().toLowerCase();
}
}
public enum ResponseParam {
STATUS, LATITUDE, LONGITUDE, NAME;
@Override
public String toString() {
return super.开发者_StackOverflow社区toString().toLowerCase();
}
}
}
Is it possible to somehow extract the enums' toString() method to a common super class/enum? Right now, I have to duplicate the toString() 8 times for each enum...
As noted by others, you cannot have enums inherit from a common class. If you are doing something more complex than you are showing in your sample code, then you could have some sort of a helper function that is static somewhere that takes in the enum and does the calculations. Enums CAN implement an interface, so you can handle complex common toStrings that way potentially.
Enums are final and also can't inherit from anything, so no. The best you can do is override toString() and delegate to a common "to-stringer" implementation so that you don't have to write the actual implementation over and over.
Because enum
has no inheritance model available to you, you can't extend anything from your enum
class, and therefore..
精彩评论