tags:

views:

243

answers:

5
+2  Q: 

Java ENUM problem

I have two Enums as follows:

enum Connector {
    AND, OR, XOR;
}

enum Component {
    ACTIVITY
}

Now, I have a variable named follower in a class Event. This variable (follower) can have (and should have) value from either of the above two Enums.

So, What datatype should I give to the follower variable?

+2  A: 
private Enum follower;

And you can make both enums implement the same interface, for example Follower, and let the field be:

private Enum<? extends Follower> follower;

But you'd better redesign the whole thing, it doesn't feel right this way.

Bozho
Can Enums have parent-child relationship just like classes? If they can, then I cam make both the enums (Connector and Component) as child of a parent enum and specified that as the datatype of the `follower` variable
Yatendra Goel
an enum is essentialyl `public YourEnum extends Enum<YourEnum>`, you you can't extend anything else. But you can implement interfaces.
Bozho
A: 

I would suggest creating a new Class called Follower. I'm not sure a single variable should have two different types even if it's possible.

I tend to think of Enums as primitive data types and your question would be like asking how do I make a variable be either int or long.

Ben
A: 
Elister
+2  A: 

You can use an interface for both enums:

interface X {}

enum Connector implements X{
    AND, OR, XOR;
}

enum Component implements X{
    ACTIVITY
}
deamon
+5  A: 

Declare an interface for the follower field.

public interface Follower {
    // any methods
}

And have both the enums implement that interface.

public enum Connector implements Follower {
    AND, OR, XOR;
}


enum Component implements Follower {
    ACTIVITY
}

Then you can declare your field:

Follower follower = Connector.OR;  

Or

Follower follower = Component.ACTIVITY;

This has a couple distinct advantage over declaring the field as an Enum<? extends Follower> (that I can think of). With this way you are free to add methods to the Follower interface without having to modify fields in the future, whereas you have no control over the Enum type, so if you decided that Followers needed a method, you would have to change the declaration in every place. This may never be the case with your scenario, but with so little cost to use this way, it's good defensive practice.

A second, slightly less important advantage, which is more about taste: it avoids the generics in the type which, when you include wildcards, can become less readable.

Grundlefleck