Java Object clone() Method
The Object clone() method is used to create and return a copy of an object.
The clone method is a shallow copy; the objects referenced by the object's attributes will only have their reference addresses copied, without reallocating memory for the referenced objects. In contrast, a deep copy recreates the referenced objects as well.
Syntax
object.clone()
Parameters
-
None .
Return Value
Returns a copy of an object.
Since Object itself does not implement the Cloneable interface, calling the clone method without overriding it will throw a CloneNotSupportedException.
Example
The following example creates the obj1 object, then copies obj1 to obj2, and outputs the variable values through obj2:
Example
class
RunoobTest
implements
Cloneable
{
//
Declare variables
String
name
;
int
likes
;
public
static
void
main
(
String
[
]
args
)
{
//
Creating objects
RunoobTest
obj1
=
new
RunoobTest
(
)
;
//
Initialize variables
obj1
.
name
=
"
Runoob
"
;
obj1
.
likes
=
111
;
//
Print output
System
.
out
.
println
(
obj1
.
name
)
;
//
Runoob
System
.
out
.
println
(
obj1
.
likes
)
;
//
111
try
{
//
Create a copy of obj1
RunoobTest
obj2
=
(
RunoobTest
)
obj1
.
clone
(
)
;
//
Output variables using obj2
System
.
out
.
println
(
obj2
.
name
)
;
//
Runoob
System
.
out
.
println
(
obj2
.
likes
)
;
//
111
}
catch
(
Exception
e
)
{
System
.
out
.
println
(
e
)
;
}
}
}
The execution result of the above program is:
Runoob
111
Runoob
111
Java Object Class