Link to home
Start Free TrialLog in
Avatar of denz_1
denz_1

asked on

how to do "enum" in java?

Hi,

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

Thanks in advance.
Avatar of Mick Barry
Mick Barry
Flag of Australia image

ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of maheshexp
maheshexp

public interface Color{
       int red = 0;
       int blue = 1;
       int green = 2;
}
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 */
  }
}
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");
    }
}
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() {
  }
}
Yes thats pretty much exactly what is suggested in the article I posted above :)