Archive for category Java Enums

enum as a class

Here I have compared enum with a class. In java, enums are like classes. What I have done here is, if we have to write a class that works like en enum, how can we do it. Though it is not of practicle use,what I have tried is to make the concept clear about enums.By comparing enum with a class, we can understand how enums work.

Here DayEnum is a enum and DayClass is class for that enum.

enum DayEnum {
SUNDAY, MONDAY
}

class DayClass {
String value;
public DayClass (String str)
{
value=str;
}

static DayClass SUNDAY, MONDAY;
static
{
SUNDAY = new DayClass("SUNDAY");
MONDAY = new DayClass("MONDAY");
}
}

public class Test
{
public static void main(String args[])
{
DayClass dayClass = DayClass.SUNDAY;
DayEnum dayEnum = DayEnum.SUNDAY;
System.out.print("dayClass "+dayClass.value+" \n dayEnum "+dayEnum);
}
}

Here SUNDAY, MONDAY are similar to static objects of Day if Day were a class.

We use enum as:
DayEnum day = DayEnum.SUNDAY;

enums are like constants. To simulate that, I have used value in DayClass. So every object of DayClass has an integer value associated with it.

Leave a comment