Junior — Middle
Will the clone() method work when called on an Object class instance without overriding it?
sobes.tech AI
Answer from AI
The clone() method is defined in the Object class and, by default, performs a shallow copy of the object. However, to call clone() on an object, the class must:
- Implement the
Cloneableinterface. If not, callingclone()will throw aCloneNotSupportedException. - Override the
clone()method with thepublicaccess modifier (inObjectit isprotected) to make it accessible from outside.
If the class does not override clone() and does not implement Cloneable, calling clone() on an object of this class will result in an exception.
Example:
class MyClass implements Cloneable {
int value;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); // shallow copy
}
}
MyClass obj = new MyClass();
MyClass copy = (MyClass) obj.clone();
If you call clone() directly on an Object class object without implementing Cloneable and overriding, it will not work.