Java : Cloneable with Examples
Cloneable (Java SE 20 & JDK 20) API Examples.
You will find code examples on most Cloneable methods.
Summary
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!