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

                Figure 7.7
Person class which implements swapping by passing a reference to a method
Person-Swapping Example—Continued
Now look at the Person class in Figure 7.7. In particular, let’s examine how the swapPerson method implements the swapping algorithm. The swapped items are the passed-in object’s name and the calling object’s name. The passed-in object is accessed via the otherPerson parameter. Note how we access the passed-in object’s name with otherPerson.name. And note how we access the calling object’s name with this.name. And finally, note how we use a temp local variable as temporary storage for otherPerson.name.
7.5 Passing References as Arguments 259
 /***************************************************************
*
Person.java
Dean & Dean
This stores, retrieves, and swaps a person's name.
***************************************************************/
*
*
*
public class Person
{
private String name;
//************************************************************
public void setName(String name)
{
}
this.name = name;
public String getName()
{
return this.name;
       Apago PDF Enhancer
// This method swaps the names for two Person objects.
}
//************************************************************
public void swapPerson(Person otherPerson)
{
String temp;
temp = otherPerson.name; ⎫
  }
// end class Person
}
otherPerson.name = this.name;
this.name = temp;
// end swapPerson
⎬   theswappingalgorithm ⎭



























































   291   292   293   294   295