Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Variables, Constructors & Methods in enum

The enum can contain variables, constructors & methods similar to normal classes of Java.
The enum cannot contain abstract method.

Example

 enum Fruits 
 {
     Apple("Red"), Banana("Yellow"), Pineapple(), Papaya("Orange"), Strawberry();
    
     String color;
    
     Fruits() // default constructor
     {
         color = "Don't know";
     }
    
     Fruits(String col)
     {
         color = col;
     }
    
     public String toString()
     {
         return color;
     }

 }

 class EnumConstructorTest 
 {
     public static void main(String args[]) 
     {
         for(Fruits f:Fruits.values())
         {
             System.out.println(f);
         }
     }
 }

Output

Red
Yellow
Don't know
Orange
Don't know

 

Leave a reply