Java Reference
In-Depth Information
Because the profit of a
DividendStock
object is computed differently from that
of a regular
Stock
object, you should override the
getProfit
method in the
DividendStock
class to implement this new behavior. An incorrect initial attempt
might look like the following code:
// this code does not compile
public double getProfit(double currentPrice) {
double marketValue = totalShares * currentPrice;
return marketValue - totalCost + dividends;
}
The preceding code has two problems. First, you can't refer directly to the various
fields that were declared in
Stock
. To get around this problem, you can add accessor
methods for each field. The second problem is that the code is redundant: It dupli-
cates much of the functionality from
Stock
's
getProfit
method, which was shown
earlier. The only new behavior is the adding of dividends into the total.
To remove this redundancy, you can have
DividendStock
's
getProfit
method
call
Stock
's
getProfit
method as part of its computation. However, since the two
methods share the same name, you must explicitly tell the compiler that you want to
call
Stock
's version. Again, you do this using the
super
keyword.
Here is the corrected code, which does compile and eliminates the previous
redundancy:
// returns the total profit or loss earned on this stock,
// including profits made from dividends
public double getProfit(double currentPrice) {
return super.getProfit(currentPrice) + dividends;
}
And here is the code for the completed
DividendStock
class:
1 // A DividendStock object represents a stock purchase that also pays
2 // dividends.
3
public class
DividendStock
extends
Stock {
4
private double
dividends; // amount of dividends paid
5
6 // constructs a new dividend stock with the given symbol
7 // and no shares purchased
8
public
DividendStock(String symbol) {
9
super
(symbol); // call Stock constructor
10 dividends = 0.0;
11 }
12
13 // returns the total profit or loss earned on this stock,
Search WWH ::
Custom Search