![]() |
VOOZH | about |
In Java, the Cloneable interface is a marker interface used to indicate that a class allows creating an exact copy of its objects. It is part of java.lang package and is primarily used with the Object.clone() method to create duplicates of objects.
Syntax
class ClassName implements Cloneable {
// class fields and methods
}
Example 1: Basic Shallow Cloning
This example shows how to create a shallow copy using the Cloneable interface and clone() method, we achieve shallow cloning by simply calling super.clone().
Original: Alice, 25 Clone: Alice, 25 After modification: Original: Alice Clone: Bob
Explanation:
Example 2: Deep Copy Example
This example demonstrates a deep copy in Java, where the object and its nested objects are fully duplicated, so changes to the clone do not affect the original.
Original City: New York Clone City: London