Discussion group, leave your messages |
|
Passing Objects to a Method 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 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:
|
Back to
CS161 JAVA Homepage |