Always assign a value equal to the number, today found some inexplicable mistakes, read a lot of articles just found that the original object assignment can not be equal to the number, equal to only the main type of assignment (String,int,float, and so on), and if the other class produced objects, with the equals number is mapped, not assignment, As long as the value of the same side, the other side of the change, that is, Java did not open up new memory, but to the original object to a name.
If you need to assign a value, you need the class to implement the Cloneable interface and implement the Clone () method.
The code is as follows |
Copy Code |
Class D implements cloneable{//implementation Cloneable interface String sex; D (String Sex) { This.sex=sex; } @Override Protected Object Clone () throws Clonenotsupportedexception { Implementing the Clone method return Super.clone (); } }
|
When assigning a value:
The code is as follows |
Copy Code |
D d=new D ("male"); D d2= (d) d.clone ()//D assign value to D2 |
If a variable in a class is not a primary type, but an object, you also need to invoke the Clone () method of that object
The following is a complete example:
The code is as follows |
Copy Code |
public class Test2 { public static void Main (string[] args) throws Clonenotsupportedexception { TODO auto-generated Method Stub D d=new D ("male"); C c=new C ("John", "M", D); C new_c= (c) c.clone ();//Invoke Clone method to assign value New_c.name= "Dick"; d.sex= "female";//d System.out.println (C.d.sex); System.out.println (C.name);
}
}
Class C implements cloneable{ String name; String age; D D; C (String name,string age,d D) throws clonenotsupportedexception{ This.name=name; This.age=age; This.d= (d) d.clone ()//Invoke the Clone method to assign the value so that even if the external d changes, the C will not change } @Override Protected Object Clone () throws Clonenotsupportedexception { TODO auto-generated Method Stub return Super.clone (); } } Class D implements cloneable{//implementation Cloneable interface String sex; D (String Sex) { This.sex=sex; } @Override Protected Object Clone () throws Clonenotsupportedexception { Implementing the Clone method return Super.clone (); } } |