The parameter passing process of objects in Java is indeed a bit messy. Here we will summarize: first, a piece of test code.
Public class main {
Public Class AA {
Public String I;
Public Int J;
}
Public static void main (string ARGs []) {
// System. Out. Print ("dddaaass ");
Main main = new main ();
Main. Test ();
}
Public void test (){
Aa a = new AA ();
A. I = "";
// Pass reference in test parameters
System. Out. Print ("Before change the. I is:" + A. I + "\ n ");
Aa B = change ();
System. Out. Print ("after change the. I is:" + A. I + "\ n ");
// Transfer method when the test parameter is returned
B. I = "B ";
System. Out. Print ("after B change the. I is:" + A. I + "\ n ");
// Method of assigning values to test objects
AA c = new AA ();
C = change ();
C. I = "C ";
System. Out. Print ("after C Change the. I is:" + A. I + "\ n ");
AA d = new AA ();
D = C;
D. I = "D ";
System. Out. Print ("after D change the. I is:" + A. I + "\ n ");
// Test the transfer method of object Value assignment
Aa g = new AA ();
G. I = "G ";
System. Out. Print ("the G. I is:" + G. I + "\ n ");
Aa h = new AA ();
H. I = G. I;
H. I = "H ";
System. Out. Print ("after H change the G. I is:" + G. I + "\ n ");
}
Public AA change (Aa aa)
{
AA. I = "ca ";
Return AA;
}
}
The test code above shows the following rules:
1. When an object is passed as a function parameter, it is passed as a reference of the original object. Changing the parameter object value will affect the original object.
2. When an object is the return value of a function, it is also a reference transfer. Changing the passed object will affect the original object.
3. When object A assigns a value to another object B (no matter whether B has passed the new space), B is a reference to object A. Changing B will affect object.
4. the only method that does not pass the reference is to use the basic data type Assignment Method to copy the object, for example, the last method in the previous example. The object is a new object, not a reference to the original object.
Supplement:
1. Although the string type in Java is also an object, when passing values, it follows the path of passing values, which is the same as the general data type. String is a special case.
Summary: In the object transfer process, it is basically carried out by reference transfer. The only non-reference transfer method is: after opening up a new object space, use the basic data type Assignment Method (you can also implement a copy Copy function ).