• Tidak ada hasil yang ditemukan

Passing Objects to a Method

Bad Ver sion

Step 4 Development: Finishing Up

4.4 Passing Objects to a Method

When calling the methods of the Bicycleand Accountclasses, we passed a numer- ical value or a String. In this section, we study how to pass an object when calling a method. Since a Stringis an object, in a sense, we actually know to pass an ob- ject as an argument to a method. However, a Stringis treated much as a primitive datum for the most part, so we will cover this topic using instances of our own class.

First, we define the Studentclass. AStudentobject has a name (String) and an email (String). Here’s the definition:

class Demo {

public void compute(int i, int j, double x) { ...

} }

Demo demo = new Demo( );

int i = 5;

int k = 14;

demo.compute( i, k, 20 );

Passing side

Receiving side

5 i

Passing side Receiving side

Memory Allocation

14 k

20

5 i

14 j

20.0 x This is a literal

constant so it has no name.

Figure 4.4 This diagram illustrates how the argument values are assigned, or passed, to the matching parameters.

class Student { //Data Members private String name;

private string email;

//Constructor public Student( ) {

name = "Unassigned";

email = "Unassigned";

}

//Returns the email of this student public String getEmail( ) {

return email;

}

//Returns the name of this student public String getName( ) {

return name;

}

//Assigns the email of this student public void setEmail(String address) {

email = address;

}

//Assigns the name of this student

public void setName(String studentName) { name = studentName;

} }

Student name

email Student( ) getEmail( ) getName( ) setEmail( String ) setName( String )

Then we define the LibraryCard class. ALibraryCard object is owned by a Student, and it records the number of books being checked out. Here’s the definition:

class LibraryCard { // Data Members

//student owner of this card private Student owner;

//number of books borrowed private int borrowCnt;

//Constructor

public LibraryCard( ) { owner = null;

borrowCnt = 0;

}

LibraryCard owner

borrowCnt LibraryCard( ) checkOut( int ) getNumberOfBooks( ) getOwnerName( ) setOwner( Student ) toString( )

Notice that we initialize the data member ownerto nullin the constructor. The value of nullmeans that owneris pointing to no object. The setOwnermethod must be called to assign a Studentobject. The method accepts a Studentobject as its para- meter and sets the data member ownerto this Studentobject.

The getOwnerNamemethod returns the name of the owner. It is defined as public String getOwnerName( ) {

return owner.getName( );

}

Because the data member ownerrefers to a Studentobject, we can get the name of this student by calling its getNamemethod.

The toStringmethod is a method that returns a string representation of an ob- ject. Because an object can have a nested structure (e.g., an object’s data member points to an instance of another class, the data members of this instance point to instances of other classes, and so forth), it is convenient for those who use the class to have a quick way to get printable information of an instance. Without such a toStringmethod, the programmer who uses the class must write a code to fetch the //numOfBooks are checked out

public void checkOut(int numOfBooks) { borrowCnt = borrowCnt + numOfBooks;

}

//Returns the number of books borrowed public int getNumberOfBooks( ) {

return borrowCnt;

}

//Returns the name of the owner of this card public String getOwnerName( ) {

return owner.getName( );

}

//Sets owner of this card to student public void setOwner(Student student) {

owner = student;

}

//Returns the string representation of this card public String toString( ) {

return "Owner Name: " + owner.getName( ) + "\n" +

" Email: " + owner.getEmail( ) + "\n" +

"Books Borrowed: " + borrowCnt;

} }

values of the data members individually. This can be quite tedious. With the toString method, she can display information of an instance by calling just one method toString.

The power of being able to pass an object to a method comes in handy when we want multiple objects to share the same object. For example, suppose a single student owns two library cards (say, one for the general library and another for the engineering library). Then we can make the data member ownerof two LibraryCard objects to refer to the same Studentobject. Here’s one such program:

class Librarian {

public static void main(String[] args) { Student student;

LibraryCard card1, card2;

student = new Student( );

student.setName("Jon Java");

student.setEmail("[email protected]");

card1 = new LibraryCard( );

card1.setOwner(student);

card1.checkOut(3);

card2 = new LibraryCard( );

card2.setOwner(student); //the same student is the owner //of the second card, too System.out.println("Card1 Info:");

System.out.println(card1.toString() + "\n");

System.out.println("Card2 Info:");

System.out.println(card2.toString() + "\n");

} }

In this program, we create one Studentobject. Then we create two LibraryCard objects. For each of these LibraryCardobjects, we pass the same student when call- ing their setOwnermethods:

card1.setOwner(student);

...

card2.setOwner(student);

After the setOwnermethod of card2is called in the mainmethod, we have the state of memory as shown in Figure 4.5.

It is critical to realize that when we say pass an object to a method, we are not sending a copy of an object, but rather a reference to the object. Figure 4.6 shows how the passing of an object is done.

Figure 4.5 The state where the data members of two objects (of LibraryCard) are pointing to the same object (of Student).

card1

:LibraryCard

student

owner

3 borrowCnt

card2

:LibraryCard owner

0 borrowCnt

“Jon Java”

:Student name

[email protected]

email

When we pass an object to a method, we are actually passing the address, or reference, of an object to the method.

It is possible to return the Studentobject itself by defining the following method:

public Student getOwner( ) { return owner;

}

We will discuss such a method that returns an instance of a programmer-defined class in Chapter 7.