Java Object Cloning Learn

Source: Internet
Author: User

There is an empty interface in the 1.java interface called the identity interface, and this interface value acts as an identity. 2. To implement a Java object clone, you need to use the object class protected Object Clone () throws Clonenotsupportedexception
method, which is protected qualified, can be accessed in this package, or in a subclass of a different package, and throws an exception.

3. If you want to implement an object clone first cloned class must implement the Cloneable interface, if this interface is not implemented, calling the Clone () method throws a Clonenotsupportedexception exception.
4. After implementing the Cloneable interface, because the Clone method in the object class cannot be accessed, we must override the Clone method
Call the Clone () method of the parent class in the Clone () method of the child class

Package Com.clone;class Cat implements cloneable{private int age;private String name;public void Setage (int. age) {This.age = age;} public int getage () {return age;} Public Cat (int age,string name) {this.age=age;this.name=name;} Public String toString () {return name: "+this.name+", Age: "+this.age;} @Overrideprotected Object Clone () throws Clonenotsupportedexception {//TODO auto-generated method Stubreturn Super.clone ();}} public class Testclone {public static void main (string[] args) {cat cat1=new cat (20, "small white"); Cat Cat2=null;try {cat2= (cat) Cat1.clone ()} catch (Clonenotsupportedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (CAT1); System.out.println (CAT2); Cat1.setage (30); System.out.println (CAT1); System.out.println (CAT2); System.out.println (CAT1==CAT2);}}

  




Java Object Cloning Learn

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.