Adding methods to an Enum

Enums introduced in Java 5.0 are just compiled java classes with some extra behavior. So you can basically do whatever you can in a normal java class inside an enum as well. That includes adding methods , class level variables and constructors to an enum.

Adding methods to an enum works just like adding methods to a normal Java class. Here’s an example of using an adding methods to an enum:

also read:

public class EnumMethods {
public enum Laptops {
	SONY(1), HP(2), DELL(3), TOSHIBA(4), ACER(5), IBM(6);
	private int rating;
	Laptops(int rating){
		this.rating = rating;
	public int getRating(){
		return rating;
public static void main(String[] args) {
	Laptops rated	= Laptops.DELL;
	System.out.println("Using enum method to get the rating of laptop.");
	switch (rated) {
		case SONY:
			System.out.println("The laptop rating is " + Laptops.SONY.getRating());
		case HP:
			System.out.println("The laptop rating is " + Laptops.HP.getRating());
		case DELL:
			System.out.println("The laptop rating is " + Laptops.DELL.getRating());
		case TOSHIBA:
			System.out.println("The laptop rating is " + Laptops.TOSHIBA.getRating());
		case ACER:
			System.out.println("The laptop rating is " + Laptops.ACER.getRating());
		case IBM:
			System.out.println("The laptop rating is " + Laptops.IBM.getRating());
			System.out.println("The laptop has got no rating.");

Given below is the output of the above program.

Using enum method to get the rating of laptop.

The laptop rating is 3

As you can see from the above example, you can add methods to an enum to add more value to the developers using your enum.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!