How do you use clone (and why to avoid it) with a simple code example?

In Java, the `clone()` method is used to create a duplicate of an object. However, its usage is often discouraged due to potential issues with shallow copies, type safety, and code readability. When an object is cloned, the default implementation of `clone()` creates a shallow copy, meaning it copies the object's fields but not the objects they reference. This can lead to unintended side effects when modifying mutable objects. Therefore, it's essential to understand the implications of using `clone()` and consider alternative approaches like copy constructors or factory methods.

public class Person implements Cloneable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public static void main(String[] args) { try { Person original = new Person("John", 30); Person copy = (Person) original.clone(); System.out.println(original != copy); // true, different instances System.out.println(original.name.equals(copy.name)); // true, same name } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }

clone Java object duplication shallow copy Cloneable interface copy constructor