toString() in enum

      No Comments on toString() in enum




Default implementation of toString() method lies in Object class. Object is the super class of all classes.

If a class does not override toString() method, then Object class toString() method will get executed for that class.

e.g.

package com.masterjavatutorial;
public class Test {
   public static void main(String args[]){
      Test  t = new Test();
      System.out.println(t.toString());
   }
}

Output of the above method is as below:

com.masterjavatutorial.Test@6bc7c054

Here in the above program, as this class does not override toString() method and so toString() of Object class gets executed.

toString() in enum:

enum class implicitly inherits Enum. Enum is the default superclass of enum classes. In the Enum , toString() method is overridden and hence, whenever toString() method is invoked on enum constants ,then toString() of Enum is executed.

Implementation of toString() in Enum is as below:

Implementation of toString() in Enum prints constant name itself.

    public String toString() {
        return name;
    }

Demo Example : toString() in enum classes

Here, toString() of Enum will get executed and It will print the name of the constant of enum on which toString() method is applied.

package com.masterjavatutorial;
public enum MONTHS {
	 
   JAN,FEB;
	
   public static void main(String args[]){
	System.out.println(MONTHS.JAN.toString());
	System.out.println(MONTHS.FEB.toString());
   }
	  
}

Output of the above program is as below:

JAN
FEB