Java Reference
In-Depth Information
40
41 // sets the current share price of this asset
42
public void
setCurrentPrice(
double
currentPrice) {
43
this.
currentPrice = currentPrice;
44 }
45 }
An abstract class is a useful hybrid that can contain both abstract and nonabstract
methods. All methods declared in an interface are implicitly abstract; they can be
declared with the abstract keyword if you wish. Declaring them without the abstract
keyword as we have done in this chapter is a commonly used shorthand for the
longer explicit form. Unfortunately, abstract classes disallow this shorthand to avoid
ambiguity.
Nonabstract classes like
Stock
and
MutualFund
are sometimes called
concrete
classes
to differentiate them from abstract classes. We can modify the
Stock
and
MutualFund
classes to take advantage of
ShareAsset
and reduce redundancy. The
following are the final versions of the
Stock
and
MutualFund
classes.
(
DividendStock
is unmodified.) Notice that the subclasses of
ShareAsset
must
implement
getMarketValue
, or we'll receive a compiler error:
1 // A Stock object represents purchases of shares of a stock.
2
public class
Stock
extends
ShareAsset {
3
private int
totalShares;
4
5 // constructs a new Stock with the given symbol and
6 // current price per share
7
public
Stock(String symbol,
double
currentPrice) {
8
super
(symbol, currentPrice);
9 totalShares = 0;
10 }
11
12 // returns the market value of this stock, which is
13 // the number of total shares times the share price
14
public double
getMarketValue() {
15
return
totalShares * getCurrentPrice();
16 }
17
18 // returns the total number of shares purchased
19
public int
getTotalShares() {
20
return
totalShares;
21 }
22
23 // records a purchase of the given number of shares of
24 // the stock at the given price per share
Search WWH ::
Custom Search