In my opinion, there are two solutions:
1) You can simulate 'C enum type' by class in Java:
class Animals {
public static int DOG = 0;
public static int CAT = 1;
public static int MOUSE = 2;
}
In this case you manually set values to enum - in C it is automatically done by compiler.
Usage of enum looks like this
public class Test {
public static void main(String[] args) {
int[] age = new int[3];
age[Animals.DOG] = 4;
age[Animals.CAT] = 3;
age[Animals.MOUSE] = 10;
for (int i = 0; i < age.length; i++) {
System.out.print(age[i] + " ");
}
}
}
I think this is bad solution because this break OOP principle of encapsulation (in class Animals).
2) You can use Java enum
enum Animals {
DOG(0), CAT(1), MOUSE(2);
int value;
private Animals(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
And example of usage
public class Test {
public static void main(String[] args) {
int[] age = new int[3];
age[Animals.DOG.getValue()] = 4;
age[Animals.CAT.getValue()] = 3;
age[Animals.MOUSE.getValue()] = 10;
for (int i = 0; i < age.length; i++) {
System.out.print(age[i] + " ");
}
}
}
In Java enum is kind of class. For more details read this.
There is no default values for enum and you have to set by yourself. In this example it is done with construcructor Animal(int value)
. Also, we cannot use Animals.DOG
like integer values but we have to use method getValue()
.