Java.lang Package Classes

Java Enum - clone() Method



The java.lang.Enum.clone() method is used to throw CloneNotSupportedException. This guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.

Syntax

protected final Object clone()
                      throws CloneNotSupportedException

Parameters

No parameter is required.

Return Value

This method does not return any value.

Exception

Throws CloneNotSupportedException, if the object's class does not support the Cloneable interface. Subclasses that override the clone method can also throw this exception to indicate that an instance cannot be cloned.

Example:

In the example below, the java.lang.Enum.clone() method returns true if the given object is equal to the given enum constant.

import java.lang.*;

public class MyClass {
  
  //creating an enum
  public enum WeekDay{
    MON("1st"), TUE("2nd"), WED("3rd"), THU("4th"), FRI("5th");

    String day;
    WeekDay(String x) {
      day = x;
    }

    String showDay() {
      return day;
    }
  }

  public static void main(String[] args) {
    
    System.out.println("Enums can never be cloned:");
    MyClass e = new MyClass() {
      protected final Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
      }
    }; 

    System.out.println("WeekDay List:");
    for(WeekDay i : WeekDay.values()) {
      System.out.println(i + " is the " + i.showDay() + " day of the week.");
    }
  }
}

The output of the above code will be:

Enums can never be cloned:
WeekDay List:
MON is the 1st day of the week.
TUE is the 2nd day of the week.
WED is the 3rd day of the week.
THU is the 4th day of the week.
FRI is the 5th day of the week.

❮ Java.lang - Enum