clone() Method
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 43 of 87.
The clone() method creates a copy of an object. To use it, your class must implement the Cloneable interface and override the clone() method from the Object class.
public class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public Person clone() {
try {
return (Person) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}Now you can create independent copies of objects:
Person original = new Person("Alice", 25);
Person copy = original.clone();
// copy is a separate object with the same valuesBy default, clone() performs a shallow copy, meaning it copies primitive values and references. If your object contains other objects as fields, both the original and clone will reference the same nested objects. For truly independent copies with nested objects, you need to implement a deep copy by also cloning those nested objects within your clone() method.
Challenge
EasyLet's build a document management system that demonstrates object cloning. You'll create a Document class that can be cloned to create independent copies, allowing users to duplicate documents while keeping the original intact.
You'll organize your code across two files:
Document.java: Create a class representing a document that supports cloning. A Document has three private fields:title(String),author(String), andversion(int). Include a constructor to initialize all fields and getter methods for each. Also add asetVersion(int version)method to update the version number.Make your Document class implement the
Cloneableinterface and override theclone()method to return aDocument. Handle theCloneNotSupportedExceptioninside the method by wrapping it in aRuntimeException.Override
toString()to return:Document[title=X, author=Y, version=Z]where X, Y, and Z are the actual field values.Main.java: Bring your Document class to life by creating a document and cloning it. You'll receive three inputs: a title (String), an author (String), and a version number (int).Create an original Document with these values, then clone it to create a copy. After cloning, modify the copy's version by incrementing it by 1 using
setVersion(). This demonstrates that the clone is truly independent from the original.Print three lines:
Original:followed by the original document's toString()Clone:followed by the cloned document's toString()Independent:followed bytrueorfalseindicating whether the original and clone are different objects (use!=comparison)
You will receive three inputs: the document title (String), the author name (String), and the version number (int).
Notice how after modifying the clone's version, the original document remains unchanged—this proves that clone() created a truly independent copy!
Cheat sheet
The clone() method creates a copy of an object. To use it, your class must implement the Cloneable interface and override the clone() method from the Object class:
public class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public Person clone() {
try {
return (Person) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}Creating independent copies:
Person original = new Person("Alice", 25);
Person copy = original.clone();
// copy is a separate object with the same valuesBy default, clone() performs a shallow copy, copying primitive values and references. If your object contains other objects as fields, both the original and clone will reference the same nested objects. For truly independent copies with nested objects, implement a deep copy by also cloning those nested objects within your clone() method.
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String title = scanner.nextLine();
String author = scanner.nextLine();
int version = scanner.nextInt();
// TODO: Create an original Document with the input values
// TODO: Clone the original document to create a copy
// TODO: Modify the clone's version by incrementing it by 1
// TODO: Print "Original: " followed by the original document
// TODO: Print "Clone: " followed by the cloned document
// TODO: Print "Independent: " followed by true/false (check if original != clone)
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System