confusion regarding clone() , Object class and Clonable Interface in Java - java

If clone() is a part of the Object class , then why do we need to implement Clonable interface to use clone()?
I have read that clone() is protected member of Object, then what is the relationship between clone() and Clonable interface.
Sorry if I sound stupid. I have just began learning Java.

Cloneable is a marker interface. It doesn't have any methods. Just to whitelist your class to make Cloneable
From docs
A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

It is highly not recommended to use clone(). I won't go into depth as this off topic but if you need more data on this please check Effective Java. Read Item 11: "Override clone judiciously".
Object.clone() has an implementation. It makes a shallow copy of the object if the object implements Cloneable.
The .clone() method does not belongs to any interface.
Having a .clone() method and implementing the Cloneable interface are completely different things.
You only need to implement the Cloneable interface if you intend to make use of Object's clone method

Related

Implementing the Clonable interface, but don't have to override the clone() method

I'm learning Java and there is something that I couldn't understand.
If I understand correctly, by implementing an interface I am forced to implement all the methods that the interface has.
But, what in the case of the Clonable? If I implement it, I'm not forced to implement the clone method. Why is this happening?
Clonable is a marker interface, which let you know that object can be cloned. You are not forced to implement clone method, because this method already exists in your class with protected access modifier (inherit from Object::clone).
Because Cloneable interface does not have such method.

What is the point in letting my class implement Cloneable?

I came across some class code that implements Clonable, the documentation states:
A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method.
Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.
I can't understand the point in implementing this class, as said in the docs the .clone method is not implemented in the interface, and I have to implement it. So why use this class? Why won't I just write a method copyClass in my class to make the object copy without the implementation of this class?
To implement the clone method, you simply do:
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
You can of course customize the method to make a deeper copy if needed.
Calling super.clone() is almost mandatory because, unless the class is final and thus can't be overridden, the clone() method must return an instance of the same class as the object on which it's called. So simply creating a new instance and copy the state will work for this class, but not for all the subclasses. Moreover, you don't always have access to all the state contained in superclasses.
In short, you make the protected clone method of Object public. And the first thing that the Object.clone() method does is (this is not the real code, but this is what the method does):
if (!(this instanceof Cloneable)) {
throw new CloneNotSupportedException();
}
So, Cloneable is just a marker interface to let the Object.clone() method know that it must not throw an exception when called.
This is one of the most badly-designed parts of Java. Usually, you should prefer using a copy contructor instead of using clone().
It allows you to write more generic code. If you have multiple classes implementing Cloneable interface, and want to pass their instances as an argument to method, you don't have to create multiple methods differing with one variable type, you can just use Cloneable t. It's the same with other interfaces. And, the same with every other interface, it's kinda multiple inheritance. Implementing those interfaces makes your code more legible too.
In addition to what others said, Cloneable is often used when implementing prototype design pattern.

What is the use of cloneable interface in java?

What is the use of implementing a cloneable interface as it is a marker interface?
I can always make a public Object clone() method in my class. What is the actual purpose of cloneable interface?
That's because the clone() method throws CloneNotSupportedException if your object is not Cloneable.
You should take a look at the documentation for clone() method.
Following is how clone() method is declared in the class Object:
protected Object clone() throws CloneNotSupportedException
Note:
Also, it's been realized that Clone is broken. This answer here in SO explains why and how you can avoid using it.
Making Cloneable a marker interface was a mistake.
That said, the one thing it does is "enable" the default implementation of clone() in Object. If you don't implement Cloneable then invoking super.clone() will throw a CloneNotSupportedException.
Some people say it's an attempt to mimic copy constructor from C++, but here's the previous similar question on StackOverflow about it: About Java cloneable
Purpose of clone() method is create a new instance (copy) of object on which it is called. As you can see in answers for use clone method your class should implements the Cloneable interface. You can choose how implement clone , you can do shallow or deep copy for your class. You can see examples http://javapapers.com/core-java/java-clone-shallow-copy-and-deep-copy/.
The purpose is specified in the javadoc. It is to specify that cloning of an object of this type is allowed.
If your class relies on the built-in implementation of clone() (provided by the Object.clone() method), then this marker interface enables field-by-field cloning. (If you call the built-in clone method on an object that doesn't implement Cloneable, you get a CloneNotSupportedException.)

Why does java.lang.Cloneable not override the clone() method in java.lang.Object?

The Java specification for the java.lang.Cloneable interface defines itself as signifying that any object that extends it also has implemented the clone() method that rests dormant within java.lang.Object. Specifically, it says that:
A class implements the Cloneable interface to indicate to the java.lang.Object#clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
To me, this means that it should be assumed that every class that extends Cloneable therefore also has a public Object clone() method within it. This makes it easy to assume that the following is a valid method:
public static makeACloneFrom(Cloneable c)
{
return c.clone();
}
however, this is not the case, as the entirety of the Cloneable source code (sans javadoc) is simply
package java.lang;
public interface Cloneable {
}
Which means that Cloneable#clone() does not exist (and trying to compile the example method above throws a compile-time error saying something like "cannot find symbol: method clone()"). Shouldn't the source code of Cloneable contain something to the effect of public Cloneable clone();?
Why aren't we allowed to assume that a class that implements Cloneable has a public Cloneable clone() method?
Because it's a poorly-designed interface.
From Effective Java (sorry, Google Books does not have a preview for the 2nd edition):
Item 11: Override clone judiciously
The Cloneable interface was intended as a mixin interface (Item
18) for objects to advertise that they permit cloning. Unfortunately,
it fails to serve this purpose. Its primary flaw is that it lacks a
clone method, and Object's clone method is protected. You
cannot, with resorting to reflection (Item 53), invoke the clone
method on an object merely because it implements Cloneable. Even a
reflective invocation may fail, as there is no guarantee that the
object has an accessible clone method.
Ugh. clone and Cloneable are broken, terribly designed, and shouldn't be used in new code. (See Effective Java item 11.)
The reason for this particular thing is that Cloneable is a confusingly implemented, magical interface such that the mere act of implementing Cloneable changes the behavior of Object.clone with reflection. Effective Java says:
...if a class implements Cloneable, Object’s clone method returns a field-by-field copy of the object; otherwise it throws CloneNotSupportedException. This is a highly atypical use of interfaces and not one to be emulated...

Confusion about cloneable interface and object.clone() in java

If I have:
class foo implements Cloneable
and then do:
bar = new foo();
bar.clone();
I get a shallow copy without needing to write any bar.clone() code like I normally would need to do when I implement an interface.
My understanding is that an interface's functions must be filled in by the class implementing it, and Object.clone() has no implementation (as per the docs, "The class Object does not itself implement the interface Cloneable")
So where does my shallow clone come from? Where is the code that implements bar.clone() if Object.clone() has no implementation? I'm confused.
Be very careful using clone. In fact, I would avoid it completely. I have never needed it. BUT... that being said, the best discussion of the topic I have ever read is by Joshua Bloch, in Effective Java. Read Item 11: "Override clone judiciously".
PLEASE do yourself a favor and read that item. I actually recommend reading that entire chapter (and the rest of the book). Everything you need to know about clone and why I caution you about it is in there.
Hope this helps.
Object.clone() has an implementation:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#clone()
This link explains the Cloneable interface:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Cloneable.html
An object must implement the Cloneable interface in order to call the clone() method, otherwise, it throws a CloneNotSupportedException.
By definition, all classes in Java extend the base Object class, and Object class has a default clone() method, even though Object itself does not implement Cloneable. The Object class's clone() method will be called if you do not override it yourself.
If I have: "class foo implements
cloneable"
and then do: bar = new foo();
bar.clone();
I get a shallow copy without needing
to write any bar.clone() code like I
normally would need to do when I
implement an interface.
That would only work if you are calling it within the class "foo", because the .clone() method inherited from Object is protected.
My understanding is that an
interface's functions must be filled
in by the class implementing it, and
Object.clone() has no implementation
(as per the docs, "The class Object
does not itself implement the
interface Cloneable")
(1) Object.clone() does have an implementation. It makes a shallow copy of the object if the object implements Cloneable. (2) The .clone() method is not part of any interface. (3) Having a .clone() method and implementing the Cloneable interface are completely separate things. You only need to implement the Cloneable interface if you intend to make use of Object's clone method; however, this is the recommended way to write a clone method for your class -- to get its copy from the superclass's clone method, which eventually goes up to Object's clone method.
My understanding is that an interface's functions must be filled in by the class implementing it, and Object.clone() has no implementation (as per the docs, "The class Object does not itself implement the interface Cloneable")
there is a difference between saying Object.clone() has no implementation
and The class Object does not itself implement the interface Cloneable
Object's clone method does have implementation, it does memory-copy of the object who called clone method.
you are right, Object class does not implement cloneable, all it does is check the object is cloneable or not .
the above answer point's you to read some book, i think i can give a quick solution
so to answer your question
So where does my shallow clone come from?
Object's clone method
Where is the code that implements bar.clone() if Object.clone() has no implementation?
it has implementation, written in native code.

Categories