04.02.2018 Views

Algorithms

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1.2 ■ Data Abstraction<br />

71<br />

O b je c t s a s a r g u m e n t s . You can pass objects as arguments to methods. This ability typically<br />

simplifies client code. For example, when we use a Counter as an argument, we are<br />

essentially passing both a name and a tally, but need only specify one variable. When<br />

we call a method with arguments, the effect in Java is as if each argument value were<br />

to appear on the right-hand side of an assignment statement with the corresponding<br />

argument name on the left. That is, Java passes a copy of the argument value from the<br />

calling program to the method. This arrangement is known as pass by value (see page<br />

24). One important consequence is that the method cannot change the value of a caller’s<br />

variable. For primitive types, this policy is what we expect (the two variables are independent),<br />

but each time that we use a reference type as a method argument we create<br />

an alias, so we must be cautious. In other words, the convention is to pass the reference<br />

by value (make a copy of it) but to pass the object by reference. For example, if we pass<br />

a reference to an object of type Counter, the method cannot change the original reference<br />

(make it point to a different Counter), but it can change the value of the object,<br />

for example by using the reference to call increment().<br />

O b j e c t s a s re t u r n va l u e s . Naturally, you can also use an object as a return value from<br />

a method. The method might return an object passed to it as an argument, as in the<br />

example below, or it might create an object and return a reference to it. This capability<br />

is important because<br />

Java methods allow only one<br />

return value—using objects<br />

enables us to write code that,<br />

in effect, returns multiple<br />

values.<br />

public class FlipsMax<br />

{<br />

public static Counter max(Counter x, Counter y)<br />

{<br />

if (x.tally() > y.tally()) return x;<br />

else return y;<br />

}<br />

% java FlipsMax 1000000<br />

500281 tails wins<br />

}<br />

public static void main(String[] args)<br />

{<br />

int T = Integer.parseInt(args[0]);<br />

Counter heads = new Counter("heads");<br />

Counter tails = new Counter("tails");<br />

for (int t = 0; t < T; t++)<br />

if (StdRandom.bernoulli(0.5))<br />

heads.increment();<br />

else tails.increment();<br />

}<br />

if (heads.tally() == tails.tally())<br />

StdOut.println("Tie");<br />

else StdOut.println(max(heads, tails) + " wins");<br />

Example of a static method with object arguments and return values

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!