Java Cloneable Interface

March 22, 2018 Oclemy Java Object Oriented Programming, Java Interfaces 1 minute, 15 seconds

This is an interface whose implementers have the capability of being cloned.

To clone is to make a copy of. Hence implementers of the Cloneable interface can be made copy of.

Cloneable Interface Definition

Cloneable is an interface hence:

public interface Cloneable{}

This interface resides in the java.lang package:

package java.lang;

This interface has more than 100 indirect subclasses. Let's see a few commonly used ones.

Class Description Result
ArrayList The most commonly used Collection type. ArrayList directly implements Cloneable. So calling the clone method will result in a new copy of the ArrayList being created.
Bundle A child of BaseBundle. Bundle maps strings to values of various data types.Bundle implements Cloneable directly. So calling the clone method will result in a new copy of the Bundle being created.
Date A date is a specific moment in time. The Date class directly implements the Cloneable interface Hence dates can be cloned using the clone() method.
Shape A Shape is a class that provides an abstract generic definition of a graphical "shape".This class to implements Cloneable. So calling the clone method will return a new Shape object.
.... ........ .....

And hundreds more classes implement this interface.

Cloneable is an Empty Interface

The cloneable interface itself is an empty interface.

However, it still is vital in that java.lang.Object, which knows how to clone via the clone() method, requires that its children implement cloneable for them to support cloning.

Failing to do so will lead to the CloneNotSupportedException being thrown.

Comments