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

The modifications we’ve made to the OneRowNim class allow us to set the instance variables of a OneRowNim object with a constructor, but there is no way for us to retrieve their values other than to use the report() method to write a message to the console. We will want to be able to ask a OneRowNim object to provide us with the number of sticks remaining and who plays next when we develop a graphical user interface for OneRowNim in the next chapter. We declared nSticks and player as private variables, so we cannot access them directly. Therefore, we will need accessor methods to get the values of each of the instance variables. Consider the following method definitions:

Annotation 2020-03-23 220652

Recall that a method’s ResultType is specified just in front of the MethodName. We want the two methods to return int values that represent OneRowNim’s instance variables. Therefore, their result types are both declared int.

Before we discuss how the value that is returned by a method is used when the method is called, let’s consider one more method definition. Many methods that return a value do a computation rather than simply returning the value of an instance variable. For example, suppose we wish to define a method for the OneRowNim class that will notify the user of an instance of the class whether the game is over. Thus we want a method that, when called, returns a true or false depending on whether or not all the sticks have been taken. gameOver() is a descriptive name of such a method and the method should have a boolean result type. This method should return true when the instance variable nSticks no longer contains a positive int value. Thus we can define:

Annotation 2020-03-23 220902

The expression (nSticks <= 0) evaluates to a false value if nSticks stores a positive value and it evaluates to true otherwise. Thus the value returned is precisely what is required.