PDA

Click to See Complete Forum and Search --> : Hwo to define own Data type - Enum


cantene
Mar 16th, 2001, 12:42 PM
Dear Friends,

I know there are ways to define one's data type using Enumeration.

How this can be done in Java?

I wish to achieve a ButtonType enum
which can carry the following 2 values only:

ButtonType {num_key, op_key}


ButtonType BigButton = num_key;

Thanks a lot.

Mar 16th, 2001, 01:53 PM
I think that loses the object oriented design goal of Java since you assigned a value like a primitive datatype.

So the only thing I can think of is to define your own class with set/get methods to check that the value being assigned is a valid value.

If you implement the Java interface java.util.Enumeration, that would only allow you to traverse the domain (perhaps overkill for two elements).


//ButtonType.java
public class ButtonType{
private int key;
public static final int num_key = 0;
public static final int op_key = 1;
public void set(int aKey) throws ButtonTypeException {
if(aKey == 0 || aKey == 1){// C Style enum right?
key = aKey;
}else{
throw new ButtonTypeException("Invalid key: " + aKey);
}
}
public int get(){
return key;
}
public ButtonType(int aKey) throws ButtonTypeException {
set(aKey);
}
public String toString(){
return "" + key;
}
}
class ButtonTypeException extends Exception{
public ButtonTypeException(String s){
super(s);
}
}

//Test.java
public class Test{
public static void main(String[] args){
try{
ButtonType bt = new ButtonType(1);
System.out.println(bt);
bt.set(ButtonType.num_key);
System.out.println(bt);
bt.set(-1);
System.out.println(bt);
}catch(ButtonTypeException bte){
System.err.println(bte);
}
}
}