Methods: Communicating with Objects

We communicate with objects using methods. Methods are executable code within each object, for which an interface has been established. Sometimes the interface is only for the object itself. Other times it is an interface accessible by other objects. This chapter discusses that topic in detail.

3.4 Retrieving Information from an Object

An Expanded OneRowNim Class

Let’s add the new methods that return values to our OneRowNim class. We might note that the report() method from the previous chapter displays the values of nSticks and player in the console window which now could be done by using the methods getSticks() and getPlayer() with System.out.println(). However, calling report() is an easy way to display the values of both instance variables but it cannot provide Redundancy and flexibility access to either variable as an int value. So let’s keep all three methods in our class definition. The inconvenience of a small amount of redundancy is outweighed by the added flexibility of being able to call all three methods.

Annotation 2020-03-23 221616

Figure 3.5 provides a UML class diagram of the expanded OneRowNim class.

Annotation 2020-03-23 221732

Let’s also consider a new main() method to test the new methods of the class. A very short list of statements that call each of the three new methods returning values is given in the main() method in Figure 3.6.

Annotation 2020-03-23 221856

The output to the console when this program is run will be:

Annotation 2020-03-23 222047

Note that the constructor sets player to 2, so player stores the value 1 after one turn.


EXERCISE 3.7 What would these segments of Java code display on the screen?

Annotation 2020-03-23 222307

EXERCISE 3.8 Suppose that an int instance variable named nMoves is added to the OneRowNim class that counts the number of moves taken in a One Row Nim game. Write a Java method for the OneRowNim class to get the value stored in nMoves.

EXERCISE 3.9 Write a method for the OneRowNim class called playerOneGoesNext() that returns a boolean value. The value returned should be true if and only if player one has the next turn.