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.2 Passing Information to an Object

Passing keyboard input to takeSticks()

To complete this section, let’s modify our main() method in Figure 3.2 so that it prompts the user to input an integer from the keyboard and then uses a Scanner object, introduced in the previous chapter, to read the integer. That integer will then be used as the argument in a call to takeSticks(). These modifications have been incorporated into the revised version of the main() method shown in Figure 3.4. If we now run this program the following output will be generated in the console window before waiting for keyboard input:

Annotation 2020-03-23 212959

Annotation 2020-03-23 213055

If the user then inputs a 2 from the keyboard, that input will be read and the takeSticks() method will remove 2 sticks. The output in the console window will now look like:

Annotation 2020-03-23 213155


EXERCISE 3.1 Explain the difference between a method declaration and a method invocation

EXERCISE 3.2 Explain the difference between a formal parameter and an argument

EXERCISE 3.3 Modify the OneRowNim class of Figure 3.4 by adding two instance variables of type String to store names of the two players. Choose names for the instance variables that would be appropriate for storing names for player one and player two. Write a method named setNames() with two string parameters which assigns the first parameter to the instance variable that you created for the name of player one. The second parameter should be assigned to the other new instance variable. 

EXERCISE 3.4 Write a statement that calls the setName() method of the previous exercise and sets the name of player one of game to “Xena” and sets the name of player two to “Yogi”.