Introduction to programming (Java) · 3.2 Value-Based Semantic Transfer, Introduction to programming pdf
Do not be influenced by Java programming ideas. Terminology in computer science --Pass-by-reference)Do not use self-speaking words. These terms are not specifically for Java. You should not learn from a Java book the special "pass by reference" that cannot be used in C, C ++, or Fortran ".
It is very easy to pass by value,Use a value assignment statement in the method body to take the form parameter as the left value.. When passing by value, the value assignment to the form parameter does not affect the real parameter, that is, the value assignment statement does not have any effect.
For foo (A a), note that you are playing a = new A () instead of playing another thing, suchA.Change ().
The text in this section can be skipped.
By defining a series of methods, you can break down the program into small modules, and method calls connect them. The formal parameters are specified during method definition, while the formal parameters are initialized by the given actual parameters.
An important topic in message transmission is:How should I pass the message parameters (real parameters) to the form parameters of the method?In a variety of programming languages, parameter transmission methods are diverse [1]. This is a trade-off between Language designers and implementers. Common parameter transmission methods are as follows:Pass-by-value)AndPass-by-reference).
From the origin of the parameter transfer mechanism, parameters in C language are passed by value, while Fortran is passed by reference, while C ++ uses both.Similar to C, Java uses the unique parameter transfer method: pass by value.
There are two issues to consider about the parameterization mechanism:
Parameter initialization,
Whether the operation on the form parameter in the method body has side effects on the real parameter.
1. method call stack
Passing by value means that when a method is called, the actual parameter (or expression) is evaluated first, The result value is copied, and then the copied value is stored in the form parameter. In short, passing by value means passing a copy.
In principle (the method stack frame is described in [7.4 Runtime storage management]). Every time Java calls a method, a new method frame is created.The format parameter (whether it is a basic type or a reference type variable) belongs to its own method frame, and the space for storing its value is allocated on the stack.. The actual parameters (or expressions) may be in heap (object domain) or belong to another method frame (another local variable). The two parameters are independent. When passing by value, if the called method modifies the value of the form parameter, only the copy is changed, and the original value of the (real parameter) is not affected at all.
Example 3: Call package OO using the lifecycle 13 method; import static tips. print. *; public class PassByValue {private void m (int x) {x + = 5;} private int max (int a, int B) {return (a> B? A: B) ;}public void foo () {int I = 1, j = 2; // The symbol before the code, indicating that the breakpoint int max = max (I, j ); m (max); I = max ;}}
Create an object and execute its foo () method. The execution process of foo () is shown in 3-6. It reflects two key points: (1) how to break down a "large code" into many small fragments (methods ), then how do these small fragments form a large whole? The hypothetical methods m (int) and max (int, int) have a long and long code. (2) Execution Process of method calls.
Figure 3 method call Process
Foo () Execution Process: (1) initialize the local variables I and j; (2) int max = max (I, j), first evaluate the method max (I, j) and then assign the value to the local variable max. To evaluate the value of method max (I, j), JVM creates a new method frame max and copies the values of the local variables I and j In the last frame foo and then assigns them to the form parameter, the foo frame is waiting. After max is executed, 2 is returned, and the max frame is popped up. 2 is assigned to max. (3) execute m (max) and create a new frame m, copy the value 2 of the real parameter max of frame foo and assign it to the x parameter. Although the value of x is changed in the m frame, the value of the real parameter is not affected.
If you are familiar with setting breakpoints in the BlueJ source code editor when learning [2.3.4 creating objects], you can go to the Method Frame call stack shown in 3-7, switch between two frames to observe that the real participation parameters have their own space in each frame.
Figure 3 switching between two frames in iis7
2. Only pass by value in Java
To learn how to pass Java parameters, you must verify the following three cases:
(1) For parameters of the basic type, operations on the form parameters in the method body will not produce side effects.
(2) when an object is referenced as a parameter, the real parameter (reference)It will not change;
(3) but using this reference as the message receiver may makeThe content of the object it points to has changed..
Example 3 limit 14 pass-by-value
Package OO; Import tips. Fraction; Import static tips. Print .*; Public class PassByValue { /// // Parameter, still pass by value //////// Private void change (Fraction frrr ){ Frrr = new Fraction (); // note this. } Private void doubleIt (Fraction f) {f. add (f );} Public void test (){ Fraction f = new Fraction (1, 3 ); P (f + ""); Change (f ); Pln (f ); // F = 1/3 Vs 1/5 Fraction f2 = new Fraction (1, 3 ); // Fraction temp = new Fraction (f2 ); DoubleIt (f2 ); // DoubleIt (temp ); Pln (f2 ); } } |
In the routine, the change (Fraction) and doubleIt (Fraction) methods take the score variable as the parameter. The execution of the test () Code shows that the change (Fraction) value on the form parameter does not affect the real parameter, while the doubleIt (Fraction) sends a message to the form parameter, this results in changes in the content of the object to which the form parameter points (that is, the object to which the real parameter points), resulting in side effects.
To avoid the possible side effects of method calling, you can take the following measures:
2. Make the referenced object belong to the unchanged class. The object (content) of the unchanged class cannot be changed, such as String.
2. Clone an object and pass its reference to the method.
3. Negative positive
Sometimes the two errors are put together, and the results are correct. A typical error example is "passing objects in Java by reference ". The description of this error has two purposes: (1) to describe what is passed by reference; (2) to emphasize that when referenced as a method parameter, passing a value still has side effects. →
Passing by reference means that the parameter in the form of a method is only the alias of the actual parameter -- the real parameter does not pass its own value but the address to the form parameter, and the two have the same data storage location. Therefore, the method changes the value of the formal parameter at any time, which actually changes the value of the real parameter.
The negative error of "passing objects by reference" in Java comes from an easy misunderstanding: the object is passed by reference (you are passing objects by reference ). The intention is that the objects in Java are not passed, but are passed for reference. However, whether it is English or Chinese, it will be confused with pass-by-reference. The so-called negative Positive is based on:
(1) objects can be passed. Objects are not passed in Java, so this is an incorrect assumption. The root cause is that people often mix terminology. "Passing objects to methods" is a common saying. For details, see [2.4.2 reference variables, references, and objects].
(2) The parameters and real parameters have the same location. If both the form parameter and the real parameter are objects, this is of course correct. The problem is that the form parameter and the real parameter (not the object) are references, just as the left and right hands point to the same moon, but the left is not the right hand, and the left is not the right hand alias/nickname.
Correct effect: the object content can be modified.
Figure 3 objects 8 will not pass
In short, the correct statement is that Object references are passed by value (Object references are passed by value ).
Exercise 3-1.: Some people may say that the phrase "object is passed through reference, but the reference is passed by value" is too harsh, and there is no clear saying that "object is passed by reference. How do you answer? |
Exercise 3-2.: Why is it wrong to say "pass by value for basic type while use by reference. |
Exercise 3-3.: What transmission mechanism should be used to transmit serialized objects in network programs? Tip: Pass the quote meaning. |
[1] http://www.yoda.arachsys.com/java/passing.html, the semantics of each type of parameter is transferred by reference.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.