Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : clone() operation calling super.clone()

Tags:

java

clone

I am not fully understanding the idea of returning super.clone() in the clone() method of a class. First of all, wouldn't that relate to it returning an object that is a superclass which contains LESS data than requested, because a superclass "is not a" subclass, but a subclass "is a" superclass. And if there were a long chain of subclasses, each calling super.clone(), why wouldn't that lead to it eventually calling Object.clone() at the root of the chain, which isn't any of the subclasses?

Sorry if that was confusing; I confuse myself sometimes

like image 664
TurtleToes Avatar asked Mar 25 '11 10:03

TurtleToes


People also ask

What does Super clone () do?

Creating a copy using the clone() method The class whose object's copy is to be made must have a public clone method in it or in one of its parent class. Every class that implements clone() should call super. clone() to obtain the cloned object reference. The class must also implement java.

What does clone () do in java?

clone() is a method in the Java programming language for object duplication. In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality.

Does clone method call constructor in java?

clone() doesn't call a constructor. You can only do this (unconditionally) if the class is final , because then you can guarantee to be returning an object of the same type as the original.

Is integer cloneable in java?

Yes, because the clone() method is protected it can be only inherited, but you can't call it on object of another class. Every class inherit Object, so you can just call clone().


1 Answers

The implementation of clone() in Object checks if the actual class implements Cloneable, and creates an instance of that actual class.

So if you want to make your class cloneable, you have to implement Cloneable and downcast the result of super.clone() to your class. Another burden is that the call to super.clone() can throw a CloneNotSupportedException that you have to catch, even though you know it won't happen (since your class implements Cloneable).

The Cloneable interface and the clone method on the Object class are an obvious case of object-oriented design gone wrong.

like image 131
Laurent Pireyn Avatar answered Sep 24 '22 13:09

Laurent Pireyn