In java, the object Value assignment is different from the ordinary variable value assignment. If we use the value = directly to assign an object value, an error is prompted, the following describes how to assign values to objects.
I have been assigning values with the equals sign. Today I found some inexplicable errors. After reading many articles, I found that the original object assignment cannot use the equals sign. Equals can only be used for assignments of the primary type (String, int, float and so on), and if it is an object produced by other classes, the equals sign is a ing, not a value assignment. As long as the value of the equals sign is changed, the value of the other side also changes, that is to say, JAVA has not opened up new memory, but just gave another name to the original object.
If you need to assign values, you need to implement the Cloneable interface of the class to implement the clone () method.
| The Code is as follows: |
Copy code |
Class D implements Cloneable {// implement the Cloneable Interface
String sex;
D (String sex ){
This. sex = sex;
}
@ Override
Protected Object clone () throws CloneNotSupportedException {
// Implement the clone method
Return super. clone ();
}
}
|
When assigning values:
| The Code is as follows: |
Copy code |
|
D d = new D ("male ");
D d2 = (D) d. clone (); // assign d to d2 |
If the variable in the class is not the main type but an object, you also need to call the clone () method of the 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 ("Zhang San", "20", d );
C new_c = (C) c. clone (); // call the clone method to assign values.
New_c.name = "Li Si ";
D. sex = "female"; // d
System. out. println (c. d. sex );
System. out. println (c. name );
}
}
Class C implements Cloneable {
String name;
String age;
D;
C (String name, String age, D) throws CloneNotSupportedException {
This. name = name;
This. age = age;
This. d = (D) d. clone (); // call the clone method to assign values, so that even if the external d changes, the values in c will not change.
}
@ Override
Protected Object clone () throws CloneNotSupportedException {
// TODO Auto-generated method stub
Return super. clone ();
}
}
Class D implements Cloneable {// implement the Cloneable Interface
String sex;
D (String sex ){
This. sex = sex;
}
@ Override
Protected Object clone () throws CloneNotSupportedException {
// Implement the clone method
Return super. clone ();
}
} |