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.1 Introduction

Methods: Communicating with Objects

OBJECTIVES 

After studying this chapter, you will 

• Understand the role that methods play in an object-oriented program. 
• Know how to use parameters and arguments to pass data to an object. 
• Understand how constructor methods are used to instantiate objects. 
• Know the difference between passing a value and passing a reference to an object. 
• Be able to design your own methods. 
• Know how to use the if-else and while control structures.

OUTLINE 

3.1 Introduction 
3.2 Passing Information to an Object 
3.3 Constructor Methods 
3.4 Retrieving Information from an Object 
3.5 Passing a Value and Passing a Reference 
3.6 Flow of Control: Control Structures 
3.7 Testing an Improved OneRowNim Special Topic: Intelligent Agents 
3.8 From the Java Library: java.lang.Object 
3.9 Object-Oriented Design: Inheritance and Polymorphism 
3.10 Drawing Lines and Defining Graphical Methods (Optional)


3.1 Introduction 

In this chapter, we take a look at Java methods and parameters. Methods and parameters are the primary mechanisms for passing information into and out of an object. We will once again focus on the OneRowNim simulation that we designed in the previous chapter. That version was sufficient to introduce us to Java objects and classes, but it was limited in its ability to communicate with other objects. In this chapter, we want to expand OneRowNim to make our simulation more realistic. We begin by learning how to pass information to an object. That will enable us to specify the number of sticks to remove using a single method. We then consider special methods called constructors, which are used to initialize an object’s state when it is created. We also learn how to retrieve information from an object. That will enable us to request a OneRowNim object for several different bits of information. Then we consider the if-else and while control structures which allow us to define more useful methods and write more realistic test programs. 


Source: R. Morelli and R. Walde, Trinity College
Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 License.