Java : Cloneable with Examples

Cloneable (Java SE 20 & JDK 20) API Examples.
You will find code examples on most Cloneable methods.


Summary

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

Class diagram

record Sample(int num, String str) implements Cloneable {
    @Override
    public Sample clone() throws CloneNotSupportedException {
        return (Sample) super.clone();
    }
}

try {
    final var sample = new Sample(100, "abc");
    final var cloned = sample.clone();

    System.out.println("Cloned! : " + cloned);

} catch (CloneNotSupportedException e) {
    System.out.println("CloneNotSupportedException!");
}

// Result
// ↓
//Cloned! : Sample[num=100, str=abc]
// Not implement Cloneable.
record Sample(int num, String str) {
    @Override
    public Sample clone() throws CloneNotSupportedException {
        return (Sample) super.clone();
    }
}

try {
    final var sample = new Sample(100, "abc");
    final var cloned = sample.clone();

    System.out.println("Cloned! : " + cloned);

} catch (CloneNotSupportedException e) {
    System.out.println("CloneNotSupportedException!");
}

// Result
// ↓
//CloneNotSupportedException!

Related posts

To top of page