Adding methods to an Enum

February 19, 2009

Java

Enums introduced in Java 5.0 are just compiled java classes with
some extra behaviour. 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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.");
	System.out.println();
	switch (rated) {
		case SONY:
			System.out.println("The laptop rating is " + Laptops.SONY.getRating());
			break;
		case HP:
			System.out.println("The laptop rating is " + Laptops.HP.getRating());
			break;
		case DELL:
			System.out.println("The laptop rating is " + Laptops.DELL.getRating());
			break;
		case TOSHIBA:
			System.out.println("The laptop rating is " + Laptops.TOSHIBA.getRating());
			break;
		case ACER:
			System.out.println("The laptop rating is " + Laptops.ACER.getRating());
			break;
		case IBM:
			System.out.println("The laptop rating is " + Laptops.IBM.getRating());
			break;
		default:
			System.out.println("The laptop has got no rating.");
			break;
	}
}
}

Given below is the output of the above program.

1
2
3
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.

email

Comments

comments