Java program to implement an Interface using an Enum

 
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:
 
  1. Create an interface.
  2. 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.

 

Submit Your Programming Assignment Details