Java Reference
In-Depth Information
Stock
symbol
total share: int
total cost
current price
getMarketValue()
getProfit()
DividendStock
symbol
total share: int
total cost
current price
dividends
getMarketValue()
getProfit()
MutualFund
symbol
total share: double
total cost
current price
getMarketValue()
getProfit()
Cash
amount
getMarketValue()
Figure 9.7
Financial classes with state and behavior
has a market value, so it would be nice to be able to compute the total market
value of all assets in an investor's portfolio, without worrying about the different
types of assets.
Because different assets compute their market values in different ways, we should
consider using an interface to represent the notion of an asset and have every class
implement the asset interface. Our interface will demand that all assets have methods
to calculate the market value and profit. The interface is a way of saying, “Classes
that want to consider themselves assets must have
getMarketValue
and
getProfit
methods.” Our interface for financial assets would be saved in a file called
Asset.java
and would look like this:
1 // Represents financial assets that investors hold.
2
public interface
Asset {
3 // how much the asset is worth
4
public double
getMarketValue();
5
6 // how much money has been made on this asset
7
public double
getProfit();
8 }
We'll have our various classes certify that they are assets by making them imple-
ment the
Asset
interface. For example, let's look at the
Cash
class. We didn't write a
getProfit
method in our previous diagram of
Cash
, because the value of cash doesn't
change and therefore it doesn't have a profit. To indicate this quality, we can write a
getProfit
method for
Cash
that returns
0.0
. The
Cash
class should look like this:
1 // A Cash object represents an amount of money held by an investor.
2
public class
Cash
implements
Asset {
3
private double
amount; // amount of money held
4
5 // constructs a cash investment of the given amount
6
public
Cash(
double
amount) {
7
this
.amount = amount;
Search WWH ::
Custom Search