Sobes.tech
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:

  1. Implement the Cloneable interface. If not, calling clone() will throw a CloneNotSupportedException.
  2. Override the clone() method with the public access modifier (in Object it is protected) 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.

Will the clone() method work when called on an Object… - sobes.tech