How Clone Method Industrial Plant Inwards Java?
The clone() is a tricky method from java.lang.Object class, which is used to do a re-create of an Object inward Java. The intention of the clone() method is simple, to furnish a cloning mechanism, exactly somehow it's implementation became tricky in addition to has been widely criticized from a long time. Anyway, nosotros volition non drib dead to classic fence of clone inward Java, at to the lowest degree for now; instead, nosotros volition attempt to larn how clone method plant inward Java. To live fair, understating cloning machinery inward Java is non slowly in addition to fifty-fifty experienced Java programmer neglect to explicate how cloning of mutable object works, or a difference betwixt deep in addition to shallow re-create inward Java.
In this three-part article, nosotros volition origin run across working of clone method inward Java, in addition to inward mo business office nosotros volition larn how to override clone method inward Java, in addition to lastly nosotros volition utter over deep re-create vs shallow copy mechanism.
The argue I chose to brand this a three-part article is to proceed the focus on 1 matter at a time. Since clone() itself is confusing enough, it's best to sympathise concept 1 past times one. In this post, nosotros volition larn what is clone method, what it does in addition to How clone method plant inward Java.
By the way, clone() is 1 of the few key methods defined past times objects, others existence equals, hashcode(), toString() along amongst hold off in addition to notify methods.
In this three-part article, nosotros volition origin run across working of clone method inward Java, in addition to inward mo business office nosotros volition larn how to override clone method inward Java, in addition to lastly nosotros volition utter over deep re-create vs shallow copy mechanism.
The argue I chose to brand this a three-part article is to proceed the focus on 1 matter at a time. Since clone() itself is confusing enough, it's best to sympathise concept 1 past times one. In this post, nosotros volition larn what is clone method, what it does in addition to How clone method plant inward Java.
By the way, clone() is 1 of the few key methods defined past times objects, others existence equals, hashcode(), toString() along amongst hold off in addition to notify methods.
What is the clone of an object inward Java?
An object which is returned past times the clone() method is known equally a clone of master copy instance. Influenza A virus subtype H5N1 clone object should follow basic characteristics e.g. a.clone() != a, which agency master copy in addition to clone are 2 split upwards object inward Java heap, a.clone().getClass() == a.getClass() in addition to clone.equals(a), which agency clone is exact re-create of master copy object. This feature is followed past times a good behaved, correctly overridden clone() method inward Java, exactly it's non enforced past times the cloning mechanism. Which means, an object returned past times clone() method may violate whatever of these rules.
By next the convention of returning an object past times calling super.clone(), when overriding clone() method, you lot tin ensure that it follows origin 2 characteristics. In gild to follow the 3rd characteristic, you lot must override equals method to enforce logical comparison, instead of physical comparing exists inward java.lang.Object.
For example, clone() method of Rectangle degree inward this method render object, which has these characteristics, exactly if you lot run the same plan past times commenting equals(), you will run across that 3rd invariant i.e. clone.equals(a) volition render false. By the way at that topographic point are a dyad of practiced items on Effective Java regarding effective role of clone method, I highly recommend to read those items subsequently going through this article.
By next the convention of returning an object past times calling super.clone(), when overriding clone() method, you lot tin ensure that it follows origin 2 characteristics. In gild to follow the 3rd characteristic, you lot must override equals method to enforce logical comparison, instead of physical comparing exists inward java.lang.Object.
For example, clone() method of Rectangle degree inward this method render object, which has these characteristics, exactly if you lot run the same plan past times commenting equals(), you will run across that 3rd invariant i.e. clone.equals(a) volition render false. By the way at that topographic point are a dyad of practiced items on Effective Java regarding effective role of clone method, I highly recommend to read those items subsequently going through this article.
How Clone method plant inward Java
protected in addition to native in Object class, therefore implemented inward native code. Since its convention to render clone() of an object past times calling super.clone() method, whatever cloning procedure eventually reaches to java.lang.Object clone() method. This method, origin checks if the corresponding object implements Cloneable interface, which is a marking interface. If that instance doesn't implement Cloneable in addition to then it throws CloneNotSupportedException inward Java, a checked exception, which is ever required to live handled spell cloning an object. If an object passes this check, than java.lang.Object's clone() method creates a shallow re-create of the object in addition to returned it to the caller.
Since Object class' clone() method creates re-create past times creating novel instance, in addition to and then copying field-by-field, similar to assignment operator, it's fine for primitives in addition to Immutable object, exactly non suited if your degree contains roughly mutable information construction e.g. Collection classes like ArrayList or arrays. In that case, both master copy object in addition to re-create of the object volition quest to the same object inward the heap. You tin preclude this past times using the technique known equally deep cloning, on which each mutable champaign is cloned separately. In short, hither is how clone method plant inward Java:
Since Object class' clone() method creates re-create past times creating novel instance, in addition to and then copying field-by-field, similar to assignment operator, it's fine for primitives in addition to Immutable object, exactly non suited if your degree contains roughly mutable information construction e.g. Collection classes like ArrayList or arrays. In that case, both master copy object in addition to re-create of the object volition quest to the same object inward the heap. You tin preclude this past times using the technique known equally deep cloning, on which each mutable champaign is cloned separately. In short, hither is how clone method plant inward Java:
1) Any degree calls clone() method on an instance, which implements Cloneable and overrides protected clone() method from Object class, to do a copy.
Rectangle rec = new Rectangle(30, 60);
logger.info(rec);
try {
logger.info("Creating Copy of this object using Clone method");
Rectangle re-create = rec.clone();
logger.info("Copy " + copy);
} catch (CloneNotSupportedException ex) {
logger.debug("Cloning is non supported for this object");
}
2) Call to clone() method on Rectangle is delegated to super.clone(), which tin live a custom superclass or past times default java.lang.Object
@Override
protected Rectangle clone() throws CloneNotSupportedException {
return (Rectangle) super.clone();
}
3) Eventually, telephone vociferation upwards reaches to java.lang.Object's clone() method, which verify if the corresponding instance implements Cloneable interface, if non in addition to then it throws CloneNotSupportedException, otherwise it creates a field-by-field re-create of the instance of that degree in addition to returned to the caller.
So inward gild for clone() method to operate properly, 2 things necessitate to happen, a class should implement Cloneable interface in addition to should override clone() method of Object class.
By the way this was this was the simplest instance of overriding clone method in addition to how it works, things gets to a greater extent than complicated amongst existent object, which contains mutable fields, arrays, collections, Immutable object, and primitives, which nosotros volition run across inward second part of this Java Cloning tutorial series.
By the way this was this was the simplest instance of overriding clone method in addition to how it works, things gets to a greater extent than complicated amongst existent object, which contains mutable fields, arrays, collections, Immutable object, and primitives, which nosotros volition run across inward second part of this Java Cloning tutorial series.
Java clone() method Example
In this article, nosotros convey non seen complexity of overriding clone method inward Java, equally our Rectangle degree is really uncomplicated in addition to alone contains primitive fields, which agency shallow cloning provided past times Object's clone() method is enough. But, this instance is of import to sympathise the procedure of Object cloning inward Java, in addition to how clone method works. Here is consummate code of this clone() method overriding example:
import org.apache.log4j.Logger;
/**
* Simple instance of overriding clone() method inward Java to sympathise How Cloning of
* Object plant inward Java.
*
* @author
*/
public class JavaCloneTest {
private static final Logger logger = Logger.getLogger(JavaCloneTest.class);
public static void main(String args[]) {
Rectangle rec = new Rectangle(30, 60);
logger.info(rec);
Rectangle re-create = null;
try {
logger.info("Creating Copy of this object using Clone method");
copy = rec.clone();
logger.info("Copy " + copy);
} catch (CloneNotSupportedException ex) {
logger.debug("Cloning is non supported for this object");
}
//testing properties of object returned past times clone method inward Java
logger.info("copy != rec : " + (copy != rec));
logger.info("copy.getClass() == rec.getClass() : " + (copy.getClass() == rec.getClass()));
logger.info("copy.equals(rec) : " + copy.equals(rec));
//Updating fields inward master copy object
rec.setHeight(100);
rec.setWidth(45);
logger.info("Original object :" + rec);
logger.info("Clonned object :" + copy);
}
}
public class Rectangle implements Cloneable{
private int width;
private int height;
public Rectangle(int w, int h){
width = w;
height = h;
}
public void setHeight(int height) {
this.height = height;
}
public void setWidth(int width) {
this.width = width;
}
public int area(){
return widthheight;
}
@Override
public String toString(){
return String.format("Rectangle [width: %d, height: %d, area: %d]", width, height, area());
}
@Override
protected Rectangle clone() throws CloneNotSupportedException {
return (Rectangle) super.clone();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Rectangle other = (Rectangle) obj;
if (this.width != other.width) {
return false;
}
if (this.height != other.height) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 47 hash + this.width;
hash = 47 hash + this.height;
return hash;
}
}
Output:
2013-05-20 23:46:58,882 0 [main] INFO JavaCloneTest - Rectangle [width: 30, height: 60, area: 1800]
2013-05-20 23:46:58,882 0 [main] INFO JavaCloneTest - Creating Copy of this object using Clone method
2013-05-20 23:46:58,882 0 [main] INFO JavaCloneTest - Copy Rectangle [width: 30, height: 60, area: 1800]
2013-05-20 23:46:58,882 0 [main] INFO JavaCloneTest - re-create != rec : true
2013-05-20 23:46:58,882 0 [main] INFO JavaCloneTest - copy.getClass() == rec.getClass() : true
2013-05-20 23:46:58,882 0 [main] INFO JavaCloneTest - copy.equals(rec) : true
2013-05-20 23:46:58,882 0 [main] INFO JavaCloneTest - Original object :Rectangle [width: 45, height: 100, area: 4500]
2013-05-20 23:46:58,882 0 [main] INFO JavaCloneTest - Cloned object :Rectangle [width: 30, height: 60, area: 1800]
From the output, you lot tin clearly run across that cloned object has the same attribute equally the master copy object inward Java. Also changing the attribute of an master copy object is non affecting the solid soil of re-create object because they alone comprise primitive fields. If they had contained whatever mutable object, it would convey affected both of them.
You tin too run across that it follow measure properties of cloned object i.e.
You tin too run across that it follow measure properties of cloned object i.e.
- clone != original,
- clone.getClass() == original.getClass(), and
- clone.equals(original).
Things to Remember - Clone method inward Java
1) The clone() method is used to do a re-create of an object inward Java. In gild to role clone() method, degree must implement java.lang.Cloneable interface in addition to override protected clone() method from java.lang.Object.
Influenza A virus subtype H5N1 telephone vociferation upwards to clone() method volition outcome inward CloneNotSupportedException if that degree doesn't implement Cloneable interface.
2) No constructor is called during cloning of Object inward Java.
3) Default implementation of clone() method inward Java provides "shallow copy" of object, because it creates re-create of Object past times creating novel instance in addition to and then copying content past times assignment, which agency if your degree contains a mutable field, in addition to then both master copy object in addition to clone volition refer to same internal object. This tin live unsafe because whatever alter made on that mutable champaign volition reverberate inward both master copy in addition to re-create object. In gild to avoid this, override clone() method to furnish the deep re-create of an object.
4) By convention, clone of an instance should live obtained past times calling super.clone() method, this volition assistance to save invariant of object created past times clone() method i.e. clone != original in addition to clone.getClass() == original.getClass(). Though these are non absolute requirement equally mentioned inward Javadoc.
5) Influenza A virus subtype H5N1 shallow re-create of an instance is fine, until it alone contains primitives in addition to Immutable objects, otherwise, you lot necessitate to modify 1 or to a greater extent than mutable fields of object returned past times super.clone(), earlier returning it to caller.
That's all on How clone method plant inward Java. Now nosotros know, what is the clone in addition to what is Cloneable interface, a dyad of things nearly clone method in addition to what does default implementation of clone method do inward Java. This information is plenty to motion ahead in addition to read second part of this Java cloning tutorial, on which nosotros volition learn, how to override clone() method inward Java, for classes composed amongst primitives, mutable in addition to immutable objects inward Java.
Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!
Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Komentar
Posting Komentar