Search code examples
javaenumsconstructorinner-classestype-erasure

How to use Nested Enums with Java Type Erasure


public enum Days {

    SUNDAY,
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY;

    public enum WeekDays{
        MONDAY,
        TUESDAY,
        WEDNESDAY,
        THURSDAY,
        FRIDAY,
    }

    public enum WeekEnds{
        SATURDAY,
        SUNDAY;
    }
}



public class InnerEnumTestClass<E extends Enum<E>> {

    public E enumtype;



    /**
     * @param enumtype
     */
    public InnerEnumTestClass(E enumtype) {
        super();
        this.enumtype = enumtype;
    }



    /**
     * @param args
     */
    public static void main(String[] args) {

        InnerEnumTestClass<Days> testObj = 
                           new InnerEnumTestClass<Days>(Days.WeekDays.MONDAY);

               // I get the following compiler error. 
               //The constructor InnerEnumTestClass<Days>(Days.WeekDays) is undefined

    }

}

As you see the Class InnerEnumTestClass accepts only type but I need the constructor to accept Days, Days.WeekDays and Days.Weekends.

How to establish this ?


Solution

  • I don't think you want to do this. You're overdoing the types. Days.MONDAY is of a different type to Days.Weekdays.MONDAY , etc. There's not much point in having them both if they're not commensurable. I think you should have one set of enum constants for the day names and an EnumSet<Days> WeekendDays = EnumSet.of(Days.SATURDAY, Days.SUNDAY). Absence of a day name from WeekendDays => it is a weekday.