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:
[code lang=”java”]
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;
}
}
}
[/code]
Given below is the output of the above program.
[code lang=”java”]
Using enum method to get the rating of laptop.
The laptop rating is 3
[/code]
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