enum inheritance, or something similar

I have a string (which is a message) that I get as input and I need to do one of 4 possible things depending on the string I know that there is eunm.valueOf() option, but I have 4 different enums, each with few possible messages.

looks something like:

public enum first{ONE,TWO,THREE}; public enum second{FOUR,FIVE,SIX}; public enum third{SEVEN,EIGHT,NINE}; public void work(String message){ //Here I want to compare message string to one of the 3 enums }

is it possible to do this in one method of the enum? or should I just try to create one, and if I get an exception try the other and so on?

-------------Problems Reply------------

As others have commented, it may be better to think through whether you really need 4 distinct enums.

But if you do, you could have them implement a common interface. Then you can map the input strings to the appropriate enum member, and call its method to accomplish what you want. Something like

public interface SomeInterface {
void doSomething();
};

public enum First implements SomeInterface {
ONE,TWO,THREE;
@Override
public void doSomething() { ... }
};
...
Map<String, SomeInterface> myMap = new HashMap<String, SomeInterface>();
for (First item : First.values()) {
myMap.put(item.toString(), item);
}
...

public void work(String message){
SomeInterface obj = myMap.get(message);
if (obj != null) {
obj.doSomething();
}
}

This assumes that the 4 possible things you want to do correspond to the 4 enums. If not, you can override the method separately for each and any enum member too, e.g.

public enum First implements SomeInterface {
ONE,
TWO {
@Override
public void doSomething() { // do something specific to TWO }
},
THREE;
@Override
public void doSomething() { // general solution for all values of First }
};

Enumerations in Java are full blown classes. Individual values can even override the behavior to meet their needs. It's pretty cool. You can use this to your advantage:

public enum Value implements Worker
{
ONE,
TWO,
THREE
{
@Override
public void doWork(String message)
{
// overrides behavior of base enum
}
},
FOUR,
/* ... */,
NINE;

private final String message;

Value() { this(""); }
Value(String message) { this.message = message; }

public void doWork(String message)
{
if (this.message.equals(message))
{
/* ... */
}
}
}

public interface Worker
{
void doWork(String message);
}

You can create a Map of them all

static final Map<String, Enum> enumMap = new LinkedHashMap<String, Enum>(){{
for(First e: First.values()) put(e.name(), e);
for(Second e: Second.values()) put(e.name(), e);
for(Third e: Third.values()) put(e.name(), e);
}};

Enum e = enumMap.get(name);

What you're really looking for is a aggregation of the other enums. The easiest way to get that is to make a new enum that puts all of those choices in a new enum. Something to this effect:

public enum Combination {
NEWONE(first.ONE), NEWTWO(first.TWO), NEWTHREE(first.THREE),
NEWFOUR(second.FOUR), NEWFIVE(second.FIVE), NEWSIX(second.SIX),
NEWSEVEN(third.SEVEN), NEWEIGHT(third.EIGHT), NEWNINE(third.NINE);

private String contents;

public Combination(first f) {
contents = f.toString();
}

public Combination(second s) {
contents = s.toString();
}

public Combination(third t) {
contents = t.toString();
}

public String toString() {
return contents;
}
}

This will more correctly aggregate the previous enums into a single data structure.

Even given your odd/even example in the comments, I don't feel multiple enums are the way to go here. I would use something like (warning, untested):

public enum Numbers {
ONE("first"), TWO("first"), THREE("first"), FOUR("second"), FIVE("second"), SIX("second"), SEVEN("third"), EIGHT("third"), NINE("third")

private String type;

Numbers(String t) { this.type = t; }
String getType { return this.type; }
}

Then you can use valueOf() to look up the enum element, and getType() to find out which of your three categories it belongs to.

It isn't entirely clear what you are asking, but perhaps you want to define a mapping between strings and constants, like this:

enum Type { FIRST, SECOND, THIRD };
Map<String, Type> mapping = new HashSet<String, Type>(){{
put("ONE", Type.FIRST);
put("TWO", Type.FIRST);
//...
put("NINE", Type.THIRD);
}};

public Type getTypeFromString(String s) {
return mapping.get(s);
}

Category:java Views:8 Time:2011-05-09

Related post

  • Emulate enum inheritance: best choice & practices 2012-02-10

    I am designing a test application (Using NUnit) that will have to navigate (through Selenium Webdriver API) through webpages. I'd like to modelize the site structure using enums to be able to tell methods where to navigate (especially NUnit methods)

  • Enums, Constructor overloads with similar conversions 2010-05-28

    Why does VisualC++ (2008) get confused 'C2666: 2 overloads have similar conversions' when I specify an enum as the second parameter, but not when I define a bool type? Shouldn't type matching already rule out the second constructor because it is of a

  • Enum inheriting from int 2011-06-14

    I've found this all over the place in this code: public enum Blah: int { blah = 0, blahblah = 1 } Why would it need to inherit from int? Does it ever need to? --------------Solutions------------- According to the documentation: Every enumeration type

  • Java enum inheritance: Is it possible to somehow extract the enums' toString() method to a common super class/enum? 2011-07-29

    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,

  • Java enum inheritance 2009-12-10

    Possible Duplicate: add values to enum Why enums in Java cannot inherit from other enums? Why is this implemented this way? --------------Solutions------------- Example stolen from here Because adding elements to an enum would effectively create a su

  • C# naming convention for enum and matching property 2009-01-30

    I often find myself implementing a class maintaining some kind of own status property as an enum: I have a Status enum and ONE Status property of Status type. How should I solve this name conflict? public class Car { public enum Status { Off, Startin

  • Can enums be subclassed to add new elements? 2009-09-12

    I want to take an existing enum and add more elements to it as follows: enum A {a,b,c} enum B extends A {d} /*B is {a,b,c,d}*/ Is this possible in Java? --------------Solutions------------- No, you can't do this in Java. Aside from anything else, d w

  • What are enums and why are they useful? 2011-01-17

    Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits to such solution. I have never used enums and I have been programing in Java for more tha

  • Why enums require an explicit cast to int type? 2011-01-18

    There is no data loss by doing this, so what's the reason for having to explicitly cast enums to ints? Would it not be more intuitive if it was implicit, say when you have a higher level method like: PerformOperation ( OperationType.Silent type ) whe

  • C# What is the best way to create an enum that is used by multiple classes? 2009-01-22

    I have an enum which is used by multiple classes. What is the best way to implement this? --------------Solutions------------- Put the enums right in your namespace (or make a new namespace for them) or Put them in a (static?) class somewhere if that

  • object is to class as enum is to -? 2009-02-06

    object is to class as enum is to ...? I'm using C# but I'd like the answer for Java as well, if there is one. Thank you, as always. --------------Solutions------------- It doesn't matter whether we're discussing C# or Java, the sentence cannot be com

  • Is it recommended to suffix all C# enums with "Enum" to avoid naming conflicts? 2009-05-28

    This stackoverflow question has an interesting discussion on how to avoid giving enums and properties the same names so that you don't have code like this: public SaveStatus SaveStatus { get; set; } It seems the accepted answer suggested to use "Stat

  • Is it possible to share an enum declaration between C# and unmanaged C++? 2009-06-05

    Is there a way to share an enum definition between native (unmanaged) C++ and (managed) C#? I have the following enum used in completely unmanaged code: enum MyEnum { myVal1, myVal2 }; Our application sometimes uses a managed component. That C# compo

  • Enum Naming Convention - Plural 2009-09-10

    I'm asking this question despite having read similar but not exactly what I want at http://stackoverflow.com/questions/495051/c-naming-convention-for-enum-and-matching-property I found I have a tendency to name enums in plural and then 'use' them as

  • typeof(System.Enum).IsClass == false 2009-11-02

    Founded that: typeof(System.Enum).IsClass == false It's become strange that System.Enum has also .IsValueType == false, but Reflector shows that it is really just an abstract class. System.Enum is a reference type like a System.ValueType and casting

  • Encapsulating a private enum 2009-12-03

    Previously I've defined enumerated types that are intended to be private in the header file of the class. private: enum foo { a, b, c }; However, I don't want the details of the enum exposed anymore. Is defining the enum in the implementation similar

  • Using enums with Pococapsule (C++ IoC-container) 2010-01-01

    Is there a way of supplying enum values as method-args in pococapsule without resorting to factory-methods? Let say I have a class that take an enum value in its constructor class A { A(myEnum val); } Using Pococapsule xml configuration: I would like

  • private inheritance and composion, which one is best and why? 2010-01-24

    suppose i have a class engin and i inherit a class car from engin class class engin { public: engin(int nobofcylinders); void start(); }; class car:private engin { public: car():e(8){} void start() { e.start(); } private: engin e; }; now the same can

  • why does vb.net not support multiple inheritance? 2010-05-03

    I've seen some discussion on why c# does not implement multiple inheritance but very little as to why it isn't supported in vb. I understand that both c# and vb are compiled down to intermediary language and so they both need to share similar restric

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.131 (s). 11 q(s)