Page 292 - Introduction to Programming with Java: A Problem Solving Approach
P. 292

                258 Chapter 7 Object-Oriented Programming—Additional Details
 /***********************************************************
*
PersonDriver.java
Dean & Dean
This class is a demonstration driver for the Person class.
***********************************************************/
*
*
*
public class PersonDriver
{
public static void main(String[] args)
{
Person person1 = new Person();
Person person2 = new Person();
person1.setName("Jonathan");
person2.setName("Benji");
System.out.println(person1.getName() + ", " +
person2.getName());
person1.swapPerson(person2);
System.out.println(person1.getName() + ", " +
person2.getName());
     }
Apago PDF Enhancer
}
// end main
// end class PersonDriver
Output:
Jonathan, Benji
Benji, Jonathan
This argument allows the called method to modify the referenced object.
 Figure 7.6 Driver for program that implements swapping by passing a reference to a method
example, rather than saying “set x to 3,” the formal-version pseudocode uses a backwards arrow and says “x ← 3.”Wefeelthatatthispoint,withseveralchaptersofJavaunderyourbelt,theformal-version pseudocode is preferable to the informal version because of its conciseness.
Would the following code work? Would it swap x and y’s contents successfully?
y← x
x← y
The first statement puts x’s original value into y. The second statement attempts to put y’s original value into x. Unfortunately, the second statement doesn’t work because y’s original value is gone (overwritten by x in the first statement). If you inserted the above code into the above algorithm, the algorithm would print:
x = 3, y = 3
That’s not what you want! The trick is to save the value of y before you wipe it out with x’s value. How do you save it? Use a temporary variable like this:
temp ← y
y← x
  Swapping requires a temporary variable.
 x ← temp























































   290   291   292   293   294