Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ENUM problem

Tags:

java

enums

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?

like image 649
Yatendra Avatar asked Feb 17 '26 22:02

Yatendra


2 Answers

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.

like image 68
Grundlefleck Avatar answered Feb 20 '26 10:02

Grundlefleck


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.

like image 31
Bozho Avatar answered Feb 20 '26 12:02

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!