A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/clonenotsupportedexception-in-java-with-examples/ below:

CloneNotSupportedException in Java with Examples

CloneNotSupportedException in Java with Examples

Last Updated : 24 Sep, 2021

CloneNotSupportedException is thrown to show that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.

Hierarchy:

Those applications which override the clone method can also throw this type of exception to indicate that an object couldn't or shouldn't be cloned.

Syntax:

public class CloneNotSupportedException extends Exception

Example of CloneNotSupportedException :

Java
// Java program to demonstrate CloneNotSupportedException

class TeamPlayer {

    private String name;

    public TeamPlayer(String name)
    {
        super();
        this.name = name;
    }

    @Override public String toString()
    {
        return "TeamPlayer[Name= " + name + "]";
    }

    @Override
    protected Object clone()
        throws CloneNotSupportedException
    {
        return super.clone();
    }
}

public class CloneNotSupportedExceptionDemo {

    public static void main(String[] args)
    {

        // creating instance of class TeamPlayer

        TeamPlayer t1 = new TeamPlayer("Piyush");
        System.out.println(t1);

        // using try catch block
        try {
            
             // CloneNotSupportedException will be thrown
             // because TeamPlayer class not implemented
             // Cloneable interface.
             
            TeamPlayer t2 = (TeamPlayer)t1.clone();
            System.out.println(t2);
        }

        catch (CloneNotSupportedException a) {
            a.printStackTrace();
        }
    }
}

Output : 



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4