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.
Is there any ways of doing 'enum' in java as in c or c++?
Thanks in advance.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
public interface Color{
int red = 0;
int blue = 1;
int green = 2;
}
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 */
}
}
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");
}
}
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() {
}
}
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 :)
Also a good discussion here:
https://www.experts-exchange.com/questions/20160731/how-to-do-enum-declaration-in-Java.html