what is the use of clone method

R

Ravi

I have java api docs, but still I am not able to understand the use of
clone() method provided by the Object class.

Can You please explain.
 
L

Lasse Reichstein Nielsen

Ravi said:
I have java api docs, but still I am not able to understand the use of
clone() method provided by the Object class.

Can You please explain.

The purpose of the clone method is to create an identical copy of
an object.

An identical copy means an instance of the same class with the same
values for all fields. Reference fields will point to the same objects,
primitive type fields will have the same value.

This copy is created without calling any constructors or other
initialization code on the object. This is somewhat acceptable, since
it cannot create an object in an uninitialized state (like the "new"
operator does before the constructors are executed).

If there are further requirements on instances of a class that are
not satisfied if you create an identical copy, then you should not
allow cloning.

Cloning is only allowed for classes that implement the marker
interface java.lang.Clonable, and which expose the clone() method
(which is protected on Object).

The typical way to use cloning is to create a class:

public class MyClass implements Clonable {
// my fields and methods ...

// make a public clone()
public Object clone() {
return super.clone();
}
}

If you need to change the behavior of the clone method, you can
change the cloned copy in your own clone method, e.g., cloning
some referenced objects too instead of referencing the same objects.

/L
 
C

Chase Preuninger

To copy the object. Lets say that you write a class that contains an
object that you want to give to te user, but you don't want them to
mess with it. They can do this because when you pass an object what
is passed is a refrence to that object, but the purpose of the clone
is to gen a copy that is not related to that object it clones.
 
L

Lew

Chase said:
...the purpose of the clone
is to gen a copy that is not related to that object it clones.

Actually, unless you implement clone() to do a deep copy, the clone could very
well be tightly coupled to the original object.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,121
Latest member
LowellMcGu
Top