Java Reference
In-Depth Information
The DividendStock simply adds an amount of dividend payments to a normal
Stock , which affects its market value. We don't need to override the getProfit
method in DividendStock , because DividendStock already inherits a getProfit
method with the following body:
return getMarketValue() - getTotalCost();
Notice that getProfit 's body calls getMarketValue . The DividendStock class
overrides the getMarketValue method, with the convenient side effect that any
other method that calls getMarketValue (such as getProfit ) will also behave dif-
ferently. This occurs because of polymorphism; since getMarketValue is overrid-
den, getProfit calls the new version of the method. The profit will be correctly
computed with dividends because the dividends are added to the market value.
The following code implements the 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 DividendStock with the given symbol
7 // and no shares purchased
8 public DividendStock(String symbol, double currentPrice) {
9 super (symbol, currentPrice); // call Stock constructor
10 dividends = 0.0;
11 }
12
13 // returns this DividendStock's market value, which is
14 // a normal stock's market value plus any dividends
15 public double getMarketValue() {
16 return super.getMarketValue() + dividends;
17 }
18
19 // records a dividend of the given amount per share
20 public void payDividend( double amountPerShare) {
21 dividends += amountPerShare * getTotalShares();
22 }
23 }
Abstract Classes
So far we have written classes, which are concrete implementations of state and
behavior, and interfaces, which are completely abstract declarations of behavior.
There is an entity that exists between these two extremes, allowing us to define some
 
Search WWH ::




Custom Search