站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

What Is a Message? - Java Tutorial 5.0 英文版

The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object-Oriented Programming Concepts

What Is a Message?

A single object alone generally is not very useful. Instead, an object usually appears as a component of a larger program or application that contains many other objects. Through the interaction of these objects, programmers achieve higher-order functionality and more complex behavior. Your bicycle hanging from a hook in the garage is just a bunch of metal and rubber; by itself, it is incapable of any activity; the bicycle is useful only when another object (you) interacts with it (by pedaling).

Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B's methods, object A sends a message to object B (see the following figure).

Object A sends a message to object B.

Objects interact by sending each other messages.

Sometimes, the receiving object needs more information so that it knows exactly what to do; for example, when you want to change gears on your bicycle, you have to indicate which gear you want. This information is passed along with the message as parameters.

The next figure shows the three parts of a message:

  • The object to which the message is addressed (YourBicycle)
  • The name of the method to perform (changeGears)
  • Any parameters needed by the method (lowerGear)

The You object sends a changeGears(lowerGear) message to the YourBicycle object

Messages use parameters to pass along extra information that the object needs — in this case, which gear the bicycle should be in.

These three parts are enough information for the receiving object to perform the desired method. No other information or context is required.

Messages provide two important benefits:

  • An object's behavior is expressed through its methods, so (aside from direct variable access) message passing supports all possible interactions between objects.
  • Objects don't need to be in the same process or even on the same machine to send messages back and forth and receive messages from each other.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.