Home » Java programming language

Java Enum clone() method with example

Enum Class clone() method: Here, we are going to learn about the clone() method of Enum Class with its syntax and example.
Submitted by Preeti Jain, on December 06, 2019

Enum Class clone() method

  • clone() method is available in java.lang package.
  • clone() method is used to give assurance that enum cannot be cloned () (i.e. we cannot copy enum objects) which is required to maintain the “singleton” behavior of the properties.
  • clone() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • clone() method is a final method so it is not overridable in child class.
  • clone() method may throw an exception at the time of not cloning an enum
    CloneNotSupportedException: This exception may throw when an object class does not implement a Cloneable interface and in that case, if child class overrides clone() method may throw CloneNotSupportedException to represent that an instance cannot be copied or closed.

Syntax:

    protected Object clone();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is Object, it returns nothing.

Example:

// Java program to demonstrate the example 
// of Object clone() method of Enum 

enum Weeks {
    SUN,
    MON,
    TUE,
    WED,
    THU,
    FRI,
    SAT;
}
public class Clone {
    public static void main(String args[]) throws CloneNotSupportedException {

        System.out.println("Enum can't be cloned");

        Clone cl = new Clone() {

            protected final Object clone() throws CloneNotSupportedException {

                return new CloneNotSupportedException();
            }
        };

        System.out.println(cl.clone());
    }
}

Output

Enum can't be cloned
java.lang.CloneNotSupportedException


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.