heartofrevel
heartofrevel

Reputation: 181

How does clone() method in java works?

I know this question has been asked so many times.

First of all Object.clone() method in java is native method i.e. it is implemented in JVM and user doesn't need to know about it's implementation.

My question is whether this method is abstract too. If not why it has to be overridden in the class that we want to clone.

And one more question . It is overridden as follows

public Object clone() {
    MyClass obj;
    try {
        obj = (MyClass)super.clone();
    } catch(CloneNotSupportedException e) {
        Statements
    }
    return obj;
}

In the 4th line of this code we called , super.clone() method , which clone() method are we calling in this line and if Object.clone() method why did we override it , we can simply cast it wherever we want to clone the Object like

MyClass obj2 = (MyClass)obj1.clone();

and is their any way to know the coding of Object.clone() method?

Upvotes: 1

Views: 1460

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200168

  1. A method cannot be native and abstract at the same time because native is a statement about a specific implementation of a method;

  2. clone must be overridden at least because Object#clone is protected to prevent access to clients in the case the object does not support cloning;

  3. in many cases clone needs to do more than Object#clone, which just makes a binary copy of the original, which amounts to a shallow clone, with all the referenced objects staying the same;

  4. there's no point in catching CloneNotSupportedException in the subclass: you should already know whether the superclass does or doesn't support cloning (it is not something which can change at runtime).

Upvotes: 3

user207421
user207421

Reputation: 310913

My question is whether it's abstract too

No it isn't, and the Javadoc already tells you that, as does the fact that Object itself isn't abstract, and it 'doesn't have to be overridden in the class we want to clone' unless you want to change the access permission, which has nothing to do with 'abstract': and you couldn't call 'super.clone()' in such an override unless it wasn't abstract.

In short, your question doesn't make much sense.

Upvotes: 0

halfbit
halfbit

Reputation: 3464

Object.clone() is not abstract. Overriding it when implementing Clonable is just a convention. (Clonable is a marker interface - like Serializable etc.)

Overriding methods (should) always call Object.clone() directly or indirectly.

I think, casting it is not necessary because Object.clone() preserves the exact class. If you catch the CloneNotSupportedException you could even return MyClass.

As Object.clone() is implemented natively you would have to look at the sources of some JVM implementation like OpenJDK.

Upvotes: 0

Related Questions