In java, how to implement an Interface using an Enum.

Enumerations serve the purpose of representing a group of named constants in a programming language. For instance, the four fits in a deck of gambling playing cards may be four enumerators named membership, diamond, heart, and spade, belonging to an enumerated kind named match. We have already discussed the basics of enum, how its declared in the preceding article. In this text, we can understand how an enum implements an interface. We by and large use enums while a way parameter can only take the fee out of a small set of feasible values approach the enter values are constant and it takes from that constant set of values. Java enum type is a special sort of java elegance that could comprise constants and methods like regular java training wherein the values are the handiest possible times of this magnificence.

This enum extends the abstract magnificence java. Lang. Enum. Bear in mind a state of affairs whilst we ought to implement some commercial enterprise common sense that's tightly coupled with a discriminatory assets of a given item or magnificence at that time we put in force an interface with enum. Reflect onconsideration on a case in which we want to merge the values of two enums into one institution and deal with them similarly, there enum implements the interface. Seeing that an enum is implicitly extending the summary elegance java. Lang. Enum, it cannot increase another magnificence or enum and additionally any class cannot make bigger enum. So it’s clean that enum cannot enlarge or can not be prolonged. However while there is a need to reap more than one inheritance enum can enforce any interface and in java, it's far feasible that an enum can put in force an interface.

Therefore, a good way to gain extensibility, the following steps are observed:

// 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