Results 1 to 2 of 2

Thread: Hwo to define own Data type - Enum

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Nov 2000
    Location
    hongkong
    Posts
    251
    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.

  2. #2
    Guest

    Thumbs up

    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);
    }
    }
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width