How do I work with enumerated values in Java since there is no language-level support for enums?

George McKinney

The best reasonable way that I know is to define a class to do it.

For instance, for an enum {MALE, FEMALE}...

public class Gender
    public static final Gender   MALE = new Gender("MALE");
    public static final Gender FEMALE = new Gender("FEMALE");

    // note PRIVATE constructor, so no one else can make Gender objects
   //  How boring :-)
   private Gender(String type)
      this.type = type;
    private String type;
    public String toString()
        return type;

Now, a method that expects a Gender argument can reasonably expect that it is either Gender.MALE or Gender.FEMALE, and a caller can use one of them but not Gender.OTHER.
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact