开发者

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)开发者_如何学Python can have (and should have) value from either of the above two Enums.

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


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.


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.


You can use an interface for both enums:

interface X {}

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

enum Component implements X{
    ACTIVITY
}


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.


Why not to have follower of type java.lang.Enum. It is parent of all enums in java. So following code works just fine.

package com.test;

enum NewEnum { one, two; }

enum Another { three, four; }

public class TestMe {

static Enum num = NewEnum.one;

public static void main(String[] args) {
    System.out.println(num.toString());
    num = Another.three;
    System.out.println(num.toString());

}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜