Java Reference
In-Depth Information
What about the similarity between mutual funds and stocks? They both store
assets that are based on shares, with a symbol, total cost, and current price. It wouldn't
work very well to make one of them a subclass of the other, though, because the type
of shares (integer or real number) isn't the same, and also because it's not a sensible
is-a relationship: stocks aren't really mutual funds, and vice versa. It might seem
excessive to have a separate class for mutual funds when the only difference is the
existence of partial shares. But conceptually, these are separate types of investments,
and many investors want to keep them separate. Also, there are some aspects of
mutual funds, such as tax ramifications and Morningstar ratings, that are unique and
that we might want to add to the program later.
Let's modify our design by making a new superclass called ShareAsset which
represents any asset that has shares and that contains the common behavior of Stock
and MutualFund . Then we can have both Stock
and MutualFund
extend
ShareAsset , to reduce redundancy.
Our previous versions of the Stock and DividendStock classes each had a
getProfit method that required a parameter for the current price per share. In order
to implement the Asset interface with its parameterless getMarketValue and
getProfit methods, we'll change our design and create a field for the current price.
We'll also add methods to get and set the value of the current price. The updated type
hierarchy is shown in Figure 9.9.
This practice of redesigning code to meet new requirements is sometimes called
refactoring.
<<interface>>
Asset
getMarketValue()
getProfit()
ShareAsset
symbol
total cost
current price
getProfit
Stock
total shares: int
getMarketValue()
MutualFund
total shares: double
getMarketValue()
Cash
amount
getMarketValue()
getProfit()
DividendStock
dividends
getMarketValue()
Figure 9.9
Updated financial class hierarchy
 
Search WWH ::




Custom Search