Overridding of Methods in Enum for its constants




Lets take an example of an enum to understand overriding of methods in enum for constants.

In the below program we would see that for each of the constants of enum, when method sayHello() is executed, then it prints the same output. This method sayHello() is common for all.

MONTHS.java

package com.masterjavatutorial;
public enum MONTHS {

  JAN,FEB,MAR,APR,MAY,JUNE,JULY,AUG,SEP,OCT,NOV,DEC;
  public void sayHello(){
     System.out.println("Hello");
  }
	  
}

Test.java

package com.masterjavatutorial;
public class Test {
    public static void main(String[] args) {
    	MONTHS vals[] = MONTHS.values();
	for(MONTHS val : vals){
	   val.sayHello();  
	}
    }

}

Output of the above program is as below:

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello

Overridding of Methods in enum for constants

sayHello() can be overridden for whichever constants we want i.e. method can be overridden.
Methods can be overridden separately for each of the constants of an enum.

The below program illustrates this overriding of methods.

MONTHS.java

package com.masterjavatutorial;
public enum MONTHS {
	  JAN,FEB,MAR,APR,
          MAY{
	     public void sayHello(){
	       System.out.println("This is month of MAY");
	     }
			  
	  },
	  
	  JUNE,JULY,AUG,SEP,OCT,NOV,
          DEC{
		public void sayHello(){
		   System.out.println("This is month of DEC");
		}
			  
	  };

	  public void sayHello(){
              System.out.println("Hello");
	  }
	  
}

IN the above class , method sayHello() is overridden for MAY and DEC. Hence, for these two overridden method should get executed.

Test.java

package com.masterjavatutorial;

public class Test {
	
	public static void main(String[] args) {
    
		MONTHS vals[] = MONTHS.values();
		for(MONTHS val : vals){
			val.sayHello();  
		}
		
	}
}


Output of the above method is as below:

Hello
Hello
Hello
Hello
This is month of MAY
Hello
Hello
Hello
Hello
Hello
Hello
This is month of DEC

The output of the above program confirms the execution of overridden methods.