Java Reference
In-Depth Information
Object-Oriented Design (OOD)
Modeling a program or system as a collection of cooperating objects,
implemented as a set of classes using class hierarchies.
Let's consider the problem of gathering information about a person's financial
investments. We've already explored a Stock example in this chapter and the previ-
ous chapter, as well as a DividendStock class to handle stocks that pay dividends.
But stocks are not the only type of asset that investors might have in their financial
portfolios. Other investments might include mutual funds, real estate, or cash.
How would you design a complete portfolio system? What new types of objects
would you write? Take a moment to consider the problem. We'll discuss an example
design next.
Designing the Classes
Each type of asset deserves its own class. We already have the Stock class from
the last chapter and its DividendStock subclass from earlier in this chapter, and
we can add classes like MutualFund and Cash . Each object of each of these types
will represent a single investment of that type. For example, a MutualFund object will
represent a purchase of a mutual fund, and a Cash object will represent a sum of
money in the user's portfolio. The available types are shown in Figure 9.6. What
data and behavior are necessary in each of these types of objects? Take a moment
to consider it.
Though each type of asset is unique, the types do have some common behavior:
Each asset should be able to compute its current market value and profit or loss, if any.
These values are computed in different ways for different asset types, though. For
instance, a stock's market value is the total number of shares that the shareholder owns,
times the current price per share, while cash is always worth exactly its own amount.
In terms of data, we decided previously that a Stock object should store the
stock's symbol, the number of shares purchased, the total cost paid for all shares,
and the current price of the stock. Dividend stocks also need to store the amount of
dividends paid. A MutualFund object should store the same data as a Stock object,
but mutual funds can hold partial shares. Cash only needs to store its own amount.
Figure 9.7 updates our diagram of types to reflect this data and behavior.
The asset types are clearly related. Perhaps we'd want to gather and store a person's
portfolio of assets in an array. It would be convenient to be able to treat any asset
the same way, insofar as they share similar functionality. For example, every asset
Stock
DividendStock
MutualFund
Cash
Figure 9.6
Financial classes
 
Search WWH ::




Custom Search