Java Reference
In-Depth Information
In our example, the program will print Superwoman lives at 235 Main .Thisisnot
the desired behavior. After all, we only changed the address of the c1 object. Why should
the address of c2 be affected? The Java creators knew about the dangers of shallow copy.
Therefore, they designed the language in a way that requires the programmer to jump
through several hoops before they can use the clone method.
1. Override the clone method as public.
2. Inherit from the interface Cloneable .
3. Catch an exception.
The interface Cloneable happens to be empty. Implementing it simply tells Java: “I know
cloning is tricky and that the default cloning only provides shallow copy. I am either satisfied
with shallow copy, or I have rewritten the clone method to implement deep copy.”
Deep copy happens when we copy the data of an object, but we also copy all inner
objects by making new instances of them. Deep copy is only possible when there are
no recursive references. For example, if an object can contain a reference to itself, then
the deep copy method may never terminate.
Java requires that all subclasses that override the clone method implement the
Cloneable interface. For example, if this interface is not implemented, then the
CloneNotSupportedException exception is raised. Therefore, we need to add exception-
handling code when dealing with the clone method. In the above code, throws Exception
means that the method can generate an exception and the exception is not handled.
Next, let us rewrite our code. This time we will use deep copy.
class FictionalCharacter implements Cloneable
private String name;
private Address address ;
public FictionalCharacter ()
public FictionalCharacter(String name, Address address)
this .name = name;
this . address = address ;
public String toString() {
return name + " lives at " + address ;
protected Object clone () throws CloneNotSupportedException {
FictionalCharacter result = (FictionalCharacter) super .clone();
result . address = (Address) address . clone () ;
return result ;
class Address implements Cloneable
private String streetName;
private int number ;
Search WWH ::

Custom Search