Java Reference
In-Depth Information
We stole some code from the
Stock
class and then made a few changes so that the
code would fit this interface. Our
Stock
code accepted the current share price as a
parameter to its
getProfit
method. Since the
getProfit
method cannot accept any
parameters if we wish to implement the interface, we'll instead store the current
share price as a field in the
ShareAsset
class and supply a
setCurrentPrice
muta-
tor method that can be called to set its proper value. We also include a constructor
that can initialize a
Stock
object with any number of shares and a total cost.
One last modification we made in creating
ShareAsset
was to include an
addCost
method, which we'll use to add a given amount to the asset's total cost. We
will need this because purchases of
Stock
sand
MutualFund
s need to update the
totalCost
field, but they cannot do so directly because it is private.
The
Stock
class can now extend
ShareAsset
to implement its remaining func-
tionality. Notice that we both extend
ShareAsset
and implement the
Asset
interface
in the class's header:
1 // A Stock object represents purchases of shares of a stock.
2 // Initial version.
3
public class
Stock
extends
ShareAsset
implements
Asset {
4
private int
totalShares;
5
6 // constructs a new Stock with the given symbol and
7 // current price per share
8
public
Stock(String symbol,
double
currentPrice) {
9
super
(symbol, currentPrice);
10 totalShares = 0;
11 }
12
13 // returns the market value of this stock, which is
14 // the number of total shares times the share price
15
public double
getMarketValue() {
16
return
totalShares * getCurrentPrice();
17 }
18
19 // returns the total number of shares purchased
20
public int
getTotalShares() {
21
return
totalShares;
22 }
23
24 // returns the profit made on this stock
25
public double
getProfit() {
26
return
getMarketValue() - getTotalCost();
27 }
28
29 // records a purchase of the given number of shares of
Search WWH ::
Custom Search