How Clone Method Plant Inwards Java?

How Clone Method Plant Inwards Java? - Hallo sahabat BEST LEARNING JAVA, Pada Artikel yang anda baca kali ini dengan judul How Clone Method Plant Inwards Java?, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan Artikel core java, Artikel core java interview question, yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : How Clone Method Plant Inwards Java?
link : How Clone Method Plant Inwards Java?

Baca juga


How Clone Method Plant Inwards Java?

The clone() is a tricky method from java.lang.Object class, which is used to practise a re-create of an Object inwards Java. The intention of the clone() method is simple, to render 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 cash inwards one's chips to classic combat of clone inwards Java, at to the lowest degree for now; instead, nosotros volition elbow grease to larn how clone method industrial plant inwards Java. To endure fair, understating cloning machinery inwards Java is non tardily 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 inwards Java.

In this three-part article, nosotros volition showtime run across working of clone method inwards Java, in addition to inwards instant role nosotros volition larn how to override clone method inwards Java, in addition to in conclusion nosotros volition verbalise 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 ane affair at a time. Since clone() itself is confusing enough, it's best to empathize concept ane yesteryear one. In this post, nosotros volition larn what is clone method, what it does in addition to How clone method industrial plant inwards Java.

By the way, clone() is ane of the few key methods defined yesteryear objects, others beingness equals, hashcode(), toString() along amongst hold off in addition to notify methods.



What is the clone of an object inwards Java?

An object which is returned yesteryear the clone() method is known every bit a clone of master copy instance. H5N1 clone object should follow basic characteristics e.g. a.clone() != a, which agency master copy in addition to clone are 2 carve upward object inwards 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 yesteryear a good behaved, correctly overridden clone() method inwards Java, exactly it's non enforced yesteryear the cloning mechanism. Which means, an object returned yesteryear clone() method may violate whatever of these rules.

By next the convention of returning an object yesteryear calling super.clone(), when overriding clone() method, you lot tin forcefulness out ensure that it follows showtime 2 characteristics. In guild to follow the tertiary characteristic, you lot must override equals method to enforce logical comparison, instead of physical comparing exists inwards java.lang.Object.

For example, clone() method of Rectangle degree inwards this method render object, which has these characteristics, exactly if you lot run the same programme yesteryear commenting equals(), you will run across that tertiary invariant i.e. clone.equals(a) volition render false. By the way at that spot are a pair of expert items on Effective Java regarding effective utilization of clone method, I highly recommend to read those items subsequently going through this article.



How Clone method industrial plant inwards Java

protected in addition to native in Object class, hence implemented inwards native code. Since its convention to render clone() of an object yesteryear calling super.clone() method, whatever cloning procedure eventually reaches to java.lang.Object clone() method. This method, showtime checks if the corresponding object implements Cloneable interface, which is a mark interface. If that instance doesn't implement Cloneable in addition to hence it throws CloneNotSupportedException inwards Java, a checked exception, which is e'er required to endure handled piece 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 yesteryear creating novel instance, in addition to and hence 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 unopen to 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 betoken to the same object inwards the heap. You tin forcefulness out forestall this yesteryear using the technique known every bit deep cloning, on which each mutable champaign is cloned separately. In short, hither is how clone method industrial plant inwards Java:



1) Any degree calls clone() method on an instance, which implements Cloneable and overrides protected clone() method from Object class, to practise 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 forcefulness out endure a custom superclass or yesteryear default java.lang.Object

    @Override
    protected Rectangle clone() throws CloneNotSupportedException {
        return (Rectangle) super.clone();
    }



3) Eventually, telephone squall upward reaches to java.lang.Object's clone() method, which verify if the corresponding instance implements Cloneable interface, if non in addition to hence 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 inwards guild for clone() method to move properly, 2 things need 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 illustration 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 inwards second part of this Java Cloning tutorial series.

Here is how  a shallow re-create of an object looks like:

 which is used to practise a re-create of an Object inwards Java How clone method industrial plant inwards Java?


Java clone() method Example

In this article, nosotros bring non seen complexity of overriding clone method inwards Java, every bit our Rectangle degree is really uncomplicated in addition to solely contains primitive fields, which agency shallow cloning provided yesteryear Object's clone() method is enough. But, this illustration is of import to empathize the procedure of Object cloning inwards Java, in addition to how clone method works. Here is consummate code of this clone() method overriding example:

import org.apache.log4j.Logger;

/**
  * Simple illustration of overriding clone() method inwards Java to empathize How Cloning of
  * Object industrial plant inwards 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 yesteryear clone method inwards 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 inwards 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 forcefulness out clearly run across that cloned object has the same attribute every bit the master copy object inwards Java. Also changing the attribute of an master copy object is non affecting the country of re-create object because they solely incorporate primitive fields. If they had contained whatever mutable object, it would bring affected both of them.

You tin forcefulness out every bit good run across that it follow criterion properties of cloned object i.e.

  • clone != original, 
  • clone.getClass() == original.getClass(), and 
  • clone.equals(original).



Things to Remember - Clone method inwards Java


1) The clone() method is used to practise a re-create of an object inwards Java. In guild to utilization clone() method, degree must implement java.lang.Cloneable interface in addition to override protected clone() method from java.lang.Object.

H5N1 telephone squall upward to clone() method volition final result inwards CloneNotSupportedException if that degree doesn't implement Cloneable interface.


2) No constructor is called during cloning of Object inwards Java.


3) Default implementation of clone() method inwards Java provides "shallow copy" of object, because it creates re-create of Object yesteryear creating novel instance in addition to and hence copying content yesteryear assignment, which agency if your degree contains a mutable field, in addition to hence both master copy object in addition to clone volition refer to same internal object. This tin forcefulness out endure unsafe because whatever alter made on that mutable champaign volition reverberate inwards both master copy in addition to re-create object. In guild to avoid this, override clone() method to render the deep re-create of an object.


4) By convention, clone of an instance should endure obtained yesteryear calling super.clone() method, this volition assistance to save invariant of object created yesteryear clone() method i.e. clone != original in addition to clone.getClass() == original.getClass(). Though these are non absolute requirement every bit mentioned inwards Javadoc.


5) H5N1 shallow re-create of an instance is fine, until it solely contains primitives in addition to Immutable objects, otherwise, you lot need to modify ane or to a greater extent than mutable fields of object returned yesteryear super.clone(), earlier returning it to caller.


That's all on How clone method industrial plant inwards Java. Now nosotros know, what is the clone in addition to what is Cloneable interface, a pair of things almost clone method in addition to what does default implementation of clone method practise inwards Java. This information is plenty to motility ahead in addition to read second part of this Java cloning tutorial, on which nosotros volition learn, how to override clone() method inwards Java, for classes composed amongst primitives, mutable in addition to immutable objects inwards Java.


Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!



Demikianlah Artikel How Clone Method Plant Inwards Java?

Sekianlah artikel How Clone Method Plant Inwards Java? kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

Anda sekarang membaca artikel How Clone Method Plant Inwards Java? dengan alamat link https://bestlearningjava.blogspot.com/2019/04/how-clone-method-plant-inwards-java.html

Belum ada Komentar untuk "How Clone Method Plant Inwards Java?"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel