|
When you are writing a Java application, writing independent classes and creating independent objects is often not sufficient. A complex functionality is usually achieved by the collaboration between various objects.
For example, in our banking application there may be many different objects; such as a bank account object that has simple responsibility of giving balance and depositing money, a transaction object that keeps record of customer’s activity etc. But what if you need to do a complex task using these objects? For instance, what if you would like to get a monthly statement of transactions on the account. Obviously, no single object can do this task independently. In other words, the objects we identified so far cannot possibly do this task without communicating with each other.
Objects communicate by sending a message or a request to another object to do a particular task. It is usually a call to a method of another object. For example, when you wish to get a monthly statement of transactions on the account, you would probably request an account-book object to prepare a monthly statement for customer. This object would communicate with other objects such as an account, customer and transaction object to the task. Figure 2.2 illustrates how the objects communicate in banking example.

Figure 2.2 Multiple object collaboration while performing a complex task
Figure 2.2 illustrates how the Account object, anAccount would communicate with various objects in a banking application. For example, it would communicate with a aCustomer object by sending a message to get customer’s details. It is likely to do so by invoking respective methods on aCustomer object such as getName(), getAdderss() etc.
When you are developing an object-oriented solution, you may find it useful to think about objects as “service providers” (rather than persons as we discussed earlier in section 2.2). In our banking example, the banking software itself will provide services to the user, and it will accomplish this by using the services offered by other objects.
|
|
In a good object-oriented design, each object should do only the tasks it is supposed to do. It should not try to do too much. For instance, Account should have behavior only account is supposed to perform. You should avoid adding behavior that is not Account’s job. If you really need such behavior, you should define another appropriate class for that behavior and let account communicate with it be sending requests (aka messages). |