how to do "enum" in java?

denz_1
denz_1 used Ask the Experts™
on
Hi,

Is there any ways of doing 'enum' in java as in c or c++?

Thanks in advance.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Mick BarryJava Developer
Top Expert 2010

Commented:
http://www.javaworld.com/<b>javaworld</b>/javatips/jw-javatip27.html

Also a good discussion here:
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20160731.html
Java Developer
Top Expert 2010
Commented:
public interface Color{
       int red = 0;
       int blue = 1;
       int green = 2;
}
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

public interface Color{
       int red = 0;
       int blue = 1;
       int green = 2;
}

public class A implements Color{
    int x;

  public A(){
     x = red;  /* used the constant value here */
  }
}

Commented:
Here is another way to do enumerations:

Maybe you could do something like this:
public class Enum {
   public static final Obj APPLE = new Fruit();
   public static final Fruit ORANGE = new Fruit();
   public static final Fruit GRAPE = new Fruit();
   public static final Fruit MELON = new Fruit();

   private Fruit() {
   }
}

Then you could implement it with:
class Driver {
    public static void main(String[] args) {
         
         Fruit newFruit;
         newFruit = Fruit.APPLE;
         
         Fruit secondFruit;
         secondFruit = Fruit.ORANGE;
         
         if(newFruit == secondFruit)
              System.out.println("This wont work");
             
          secondFruit = Fruit.APPLE;
         
         if(newFruit == secondFruit)
              System.out.println("Aha!  There we go");
    }
}

Commented:
oops, change the first class to:

public class Fruit {
  public static final Fruit APPLE = new Fruit();
  public static final Fruit ORANGE = new Fruit();
  public static final Fruit GRAPE = new Fruit();
  public static final Fruit MELON = new Fruit();

  private Fruit() {
  }
}
Mick BarryJava Developer
Top Expert 2010

Commented:
Yes thats pretty much exactly what is suggested in the article I posted above :)
Mick BarryJava Developer
Top Expert 2010

Commented:

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial