Week 10

Back ] Up ] Next ]

Discussion group, leave your messages

Home
Week 1
Week 2
Week 3
Week 4
Week 5
Week 6
Week 7
Week 8
Week 9
Week 10
Week 11
Week 12

Passing Objects to a Method

When you pass an object as an argument to a method, the mechanism that applies is called pass-by-­reference, because a copy of the reference contained in the variable is transferred to the method, not the object itself. The effect of this is shown in the following diagram.

This illustration presumes we have defined a method, changeRadius ( ), in the class Sphere that will alter the radius value for an object, and that we have a method change () in some other class that calls changeRadius ( ). When the variable ball is used as an argument to the method change O, the pass-by-reference mechanism causes a copy of ball to be made and stored in s. The variable ball just stores a reference to the Sphere object, and the copy contains that same reference and therefore refers to the same object. No copying of the actual object occurs. This is a major plus in terms of efficiency when passing arguments to a method. Objects can be very complex involving a lot of instance variables. If objects themselves were always copied when passed as arguments, it could be very time consuming and make the code very slow.

 Since the copy of ball refers to the same object as the original, when the changeRadius () method is called the original object will be changed. You need to keep this in mind when writing methods that have objects as parameters because this is not always what you want.

 In the example shown, the method change () returns the modified object. In practice you would probably want this to be a distinct object, in which case you would need to create a new object from s.

Remember that this only applies to objects. If you pass a variable of type int or double to a method for example, a copy of the value is passed. You can modify the value passed as much as you want in the method, but it won’t affect the original value.

From: Beginning JAVA 2, Ivor Horton

Another Example:

// c03PassObject.java
// Passing objects to methods may not be what
// you're used to.

class Letter {

char c;

}

public class PassObject {

    static void f(Letter y) {
    y.c = 'z';

}

public static void main(String[] args) {

    Letter x = new Letter();
    x.c = 'a';
    System.out.println(
"1 x.c " + x.c);
    f(x);
    System.out.println(
"2 x.c " + x.c);

}

} ///~

The output shows this
1 x.c a
2 x.c z

Links:

bulletPassing information to methods
 

Back to CS161 JAVA Homepage
This page was last modified January 10, 2002
wmorales@pcc.edu