Pseudo-Cloning of Java objects

Source: Internet
Author: User

public class employee{private string name;private int age;public string getName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public Employee (String name, int.) {this.name = Name;this.age = age;} Public Employee () {} @Overridepublic String toString () {return ' employee [name= + name + ', age= ' + Age + '] ";}}

/**

* In Java you can use "=" for a base type to clone, at which point two variables are not related except for equality

* But for reference types it is not easy to clone with "=", which is related to the memory space of Java.

* Divide the memory space into two blocks in Java, that is, heaps and stacks.

* Save base types and reference variables in the stack

* Save objects in the heap

* For reference variables, using "=" will modify the reference instead of copying the objects in the heap, at which point the two reference variables will

* point to the same object

* So one variable changes the other variable

*/

public static void Main (string[] args) {System.out.println ("before Cloning:"); Employee EMP1 = new Employee (), Emp1.setname ("Zhang xx"), Emp1.setage (30); SYSTEM.OUT.PRINTLN ("Employee 1 Information:" +EMP1); System.out.println ("after cloning"); Employee EMP2 = emp1;emp1.setname ("Li xx"); Emp1.setage (24); SYSTEM.OUT.PRINTLN ("Employee 1 Information:" +EMP1); System.out.println ("Employee 2 Information:" +EMP2); System.out.println ("is the same object:" + (EMP1==EMP2));}

The results of the operation are as follows:

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M00/8E/D7/wKioL1jMoiCjmGl1AABCi4svfVM645.jpg "title=" 36020170315204858576.jpg "alt=" Wkiol1jmoicjmgl1aabci4svfvm645.jpg "/>

This article is from the "It Rookie" blog, make sure to keep this source http://mazongfei.blog.51cto.com/3174958/1907842

Pseudo-Cloning of Java objects

Related Article

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.