Enum
- All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else.
- Every enum constant is always implicitly public static final. Since it is static, we can access it by using enum Name. Since it is final, we can’t create child enums.
public enum Day
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
//internal implementation of Day
public enum Day
{
public static final Day Monday = new Day();
public static final Day Tuesday = new Day();
public static final Day Wednesday = new Day();
public static final Day Thursday = new Day();
public static final Day Friday = new Day();
public static final Day Saturday = new Day();
public static final Day Sunday = new Day();
}
public class E
{
public static void main(String args[])
{
Day d = Day.Monday;
System.out.println(d);
//valueOf
System.out.println(d.valueOf("Sunday"));
//values
for(Day e : Day.values())
System.out.println(e);
System.out.println(Day.Saturday.ordinal());
}
}
main method in enum
public enum Day
{
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;
public static void main(String args[])
{
Day d = Day.Sunday;
System.out.println(d);
}
}
enum and constructors
- Enum constants are followed by arguments which are passed to the enum constructor
- Constructor is executed separately for each enum constant at the time of enum class loading
- Not able to create enum objects explicitly and hence we can’t invoke enum constructor directly
public enum Car
{
Camery("Toyota", 2010),
Accord("Honda", 2016),
Acura("Honda", 2000),
Century("Buick", 1998);
private final String maker;
private final int year;
Car(String m, int y)
{
maker = m;
year = y;
}
public String getMaker()
{
return maker;
}
public int getYear()
{
return year;
}
}
public class CarTest
{
public static void main(String args[])
{
for(Car b : Car.values())
System.out.printf("%s: %s %d\n", b, b.getMaker(), b.getYear());
Car c = Car.Accord;
System.out.printf("%s %d\n", c.getMaker(), c.getYear());
}
}
Access enum with index
public class E
{
public static void main(String args[])
{
//index
for(int i = 0, len = Day.values().length; i < len; i++)
System.out.println(Day.values()[i]);
}
}
Compare enum objects
- compareT(), negative, zero, positive integers for less than, equals, and greater than
- The natural order implemented by this method is the order in which the constants are declared
public class E
{
public static void main(String args[])
{
Day a = Day.Monday;
Day b = Day.Tuesday;
if(a.compareTo(b) < 0)
System.out.printf("%s < %s\n", a, b);
}
}
Reference