Friday, January 28, 2011

Enumeration improved with Generics

Google is your friend, Wiki is your teacher is very true. I have been reading on the bus ride during the CNY trip and learnt some power concept for OOP in java especially the use of generics. Below is the code I improved on AbstractEnum class which will now be even more flexible than ever.

public abstract class AbstractEnum<INPUT_TYPE>{
    private final INPUT_TYPE k;
    private static int nextOrdinal = 0;
    private final int ordinal = nextOrdinal++;
   
    protected AbstractEnum(INPUT_TYPE k){
      this.k = k;
    }
   
    public INPUT_TYPE getValue(){
      return this.k;
    }
   
    public int getOrdinal(){
      return this.ordinal;
    }
   
    //override equals method   
    public boolean equals(Object o){
        AbstractEnum objE =  (AbstractEnum) o;
        return ( this.ordinal == objE.getOrdinal() );
    }
}

Here's the implementation. Look much cleaner than before isn't it?

public class DayImpl extends AbstractEnum<String>{

    protected DayImpl(String name) {
        super(name);
        // TODO Auto-generated constructor stub
    }
   
    //creating your enum
    public static final DayImpl Mon = new DayImpl("monday");
    public static final DayImpl Tue = new DayImpl("tuesday");
    public static final DayImpl Wed = new DayImpl("wednesday");
    public static final DayImpl Thur = new DayImpl("thursday");
    public static final DayImpl Fri = new DayImpl("friday");
    public static final DayImpl Sat = new DayImpl("saturday");
    public static final DayImpl Sun = new DayImpl("sunday");
}

No comments:

Post a Comment