Enumerations serve
the aim of representing
a gaggle of named constants
during a programing language .
for instance , the 4 suits
during a deck of playing cards
could also be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit.
we've already discussed
the fundamentals of enum, how it's declared
within the previous article.
during this article,
we'll understand how an enum implements an interface.
We primarily use enums when
a way parameter can only take
the worth out of
alittle set of possible values means the input values are fixed and it takes from that fixed set of values. Java enum type
may be a special
quite java class
which may contain constants and methods like normal java classes where the values are
the sole possible instances of this class. This enum extends the abstract class java.lang.Enum. Consider a situation
once we need to implement some business logic which is tightly
including a discriminatory property of a given object or class at
that point we implement an interface with enum.
believe a case where
we'd like to merge the values of two enums into one group and treat them similarly, there Enum implements the interface.
Since an enum is implicitly extending the abstract class
java.lang.Enum, it
can't extend
the other class or enum and also any class
can't extend enum. So it’s clear that enum
can't extend or
can't be extended. But when
there's a requirement to realize multiple inheritance enum can implement any interface and in java,
it's possible that an enum can implement an interface. Therefore,
so as to realize extensibility,
the subsequent steps are followed:
- Create an interface.
- After creating an interface, implement that interface by Enum.
The following is the code which demonstrates the implementation of an interface in an enum:
// Java program to demonstrate
// how an enum implements an
// interface
// Defining an interface
interface week {
// Defining an abstract method
public int day();
}
// Initializing an enum which
// implements the above interface
enum Day implements week {
// Initializing the possible
// days
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday;
public int day()
{
return ordinal() + 1;
}
}
// Main Class
public class Daycount {
public static void main(String args[])
{
System.out.println("It is day number "
+ Day.Wednesday.day()
+ " of a week.");
}
}
Output:
It is day number 3 of a week.