|
发表于 2020-7-18 16:00:01
|
显示全部楼层
1, Java uses "Pass by Value" in method argument passing.
For primitive variables, the actual primitive value is stored.
For reference variables, which refer to instances of classes, the object reference is stored. This object reference is also called "pointer to the actual Object instance" or "the way (or the path) to reach the actual Object instance".
When a primitive variable is passed as an argument to a method, a separated copy of the variable value is passed to the method. This copy of the value can be changed within the called method, but the orginal primitive variable is not affected.
When a reference variable is passed as an argument to a method, a separated copy of the varialbe value is passed to the method as well. Over here, this variable value is the object reference (or the way to reach the actual Object instance). It's NOT the actual Object instance. The called method knows this object reference (the way to reach the original Object instance), so it can reach the original Object instance. This is why the called method can change the original Object instance (only if the Object instance is mutable).
Let's see the example given. Reference variable "base" is pointing a mutable "Base" instance. That's why the "changeBase" method changed the original "Base" instance.
2, String class is final, which means String instances are immutable. If a String reference variable is passed as an argument to a method, the method can reach the original String instance, but it can NEVER change it.
In the given example, String variable "str" is assigned with value "1234". When "str" is passed in to method "changeStr", a copy of this String reference varialbe is passed to method "changeStr". Let's call this copy with the name "strCopy". Now, both "str" and "strCopy" point to the same String instance (value "1234"). Inside method "changeStr", String reference variable "str" (which is actually "strCopy") is assigned with new value, which points to another String instance (value "welcome"). The original String reference variable is not affected. It still points to the String instance (value "1234"). |
|