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