First write a simple employee to test the use.
class Employee { private String name; Public Employee (String name) { this. Name = name; } Public String GetName () { return name; } Public void setName (String name) { this. Name = name; }}
Then write a function, pass in a Emplyee object, modify the name, if the function completes the original employee's name value changes, according to our understanding, will be considered as a reference pass.
Public Static void Main (string[] args) { new Employee ("Alice"); New Employee ("Bob"); ChangeName (a); System.out.println (A.getname ()); System.out.println (B.getname ()); } Public Static void changename (Employee x) { x.setname ("Fly"); }
Execution Result:
Fly
Bob
But there is also a test case that swaps two of objects. If a reference is passed, the name of the two object is exchanged after the function execution finishes. Let's try it now.
Public Static void Main (string[] args) { new Employee ("Alice"); New Employee ("Bob"); Swap (A, b); System.out.println (A.getname ()); System.out.println (B.getname ()); } Public Static void Swap (employee x, employee y) { = x; = y; = t; }
Execution Result:
Alice
Bob
But they have not changed anything. What's the situation?! Has it become a value transfer?
The final answer is indeed a value pass . The first example gives you the feeling that a reference is passed because the value of the incoming function is a copy of the object reference. (the phrase in C is a copy of a pointer, that is, a copy of the address.) )
At this point, we'll write the last example, modifying the name value of x in the swap function.
Public Static void Swap (employee x, employee y) { = x; = y; = T; X.setname ("Joyce");
Execution Result:
Alice
Joyce
See, the X-Exchange reference is B, so after modifying X, B changes. The second time because there is no modification, the function after the end of nothing, after all, just a copy of the reference ~
Java is a value pass, and a value is a copy of an object reference.
Whether Java is a value pass or a reference pass