Java Reference
In-Depth Information
The call to the superclass's constructor using super must be the first statement in a
subclass's constructor. If you reverse the order of the statements in DividendStock 's
constructor and set the dividends before you call super , you'll get a compiler error
like the following:
Call to super must be first statement in constructor
super(symbol); // call Stock constructor
Here's the DividendStock class so far. The class isn't complete yet because you
haven't yet implemented the behavior to make dividend payments:
// A DividendStock object represents a stock purchase that also pays
// dividends.
public class DividendStock extends Stock {
private double dividends; // amount of dividends paid
// constructs a new dividend stock with the given symbol
// and no shares purchased
public DividendStock(String symbol) {
super(symbol); // call Stock constructor
this.dividends = 0.0;
}
...
}
DividendStock Behavior
To implement dividend payments, we'll begin by writing a method called
payDividend that accepts a dividend amount per share and adds the proper amount
to DividendStock 's dividends field. The amount per share should be multiplied by
the number of shares the shareholder owns:
// records a dividend of the given amount per share
public void payDividend(double amountPerShare) {
dividends += amountPerShare * getTotalShares();
}
The dividend payments that are being recorded should be considered to be profit
for the stockholder. The overall profit of a DividendStock object is equal to the
profit from the stock's price plus any dividends. This amount is computed as the market
value (number of shares times current price) minus the total cost paid for the shares,
plus the amount of dividends paid.
Notice that you don't need to use super.getTotalShares in the preceding
code. You have to use the super keyword only when you are accessing overridden
methods or constructors from the superclass. DividendStock doesn't override the
getTotalShares method, so you can call it without the super keyword.
 
Search WWH ::




Custom Search