nick zoum nick zoum - 23 days ago 6
Java Question

Create group of Enums with common property in Java

I have a

Class
that contains a group of
public Strings
. And I would like to group them, so that accessing them from another
Class
is less confusing.

For example the following line would print the field.

System.out.println(ClassName.GroupName.FIELD);


The way I've implemented this is:

public class ClassName{
public static class GroupName{
public static final String FIELD = "TEXT";
public static final String FIELD1 = "TEXT";
}
public static class GroupName1{
public static final String FIELD2 = "TEXT";
}
}


But I think using
enums
for this kind of task would be more efficient.

The problem is that I would have to write this for each group:

public enum GroupName{
FIELD ("TEXT"), FIELD1 ("TEXT");

private String text;

Extra(String text) {
this.text = text;
}

public String toString() {
return text;
}
}


So the
Class
would become too big, and frankly it wouldn't look as neat.

I would prefer it if I could do something like:

public class EnumInterface{
private String text;

public EnumInterface(String text){
this.text = text;
}

public String toString(){
return text;
}

}

public enum GroupName extends EnumInterface{
FIELD("TEXT"), FIELD1("TEXT")
}


But unfortunately
enums
cannot extend
classes
and if
EnumInterface
was an actual
interface
then I would not be able to have the
field
,
constructor
or
method
there.

Any recommendations?

Answer

As instructed by Andy Turner, here, I am still using Classes over Enums.

But I've also made this private constructor:

private GroupName(){
    throw new UnsupportedOperationException("This class cannot be instantiated.");
}

So that this class cannot be instantiated under any circumstances.