← Back to libraryQuestion 25 of 273
JavaIntermediate

Object Cloning

📖 Detailed Explanation:

Cloning creates a copy of an object using the `clone()` method of the Object class. To use it, a class must implement the Cloneable marker interface; otherwise, it throws CloneNotSupportedException. The Object.clone() method performs a shallow copy by default.

🎯 Scenario-Based Interview Question:

What is the difference between a Copy Constructor and the clone() method?

💡 Note:

Modern Java developers often prefer Copy Constructors or serialization for copying objects. The clone() method is considered poorly designed and lacks type safety. Consider using: public Employee(Employee other) { this.id = other.id; this.name = new String(other.name); }