Java Reference
In-Depth Information
It may seem unnecessarily restrictive that a class isn't able to examine the fields it
has inherited, since those fields are part of the object. The reason Java is built this
way is to prevent a subclass from violating the encapsulation of the superclass. If a
superclass object held sensitive data and subclasses were allowed to access that data
directly, they could change it in malicious ways the superclass did not intend.
The solution here is to use accessor or mutator methods associated with our fields
to access or change their values. The Stock class doesn't have a public accessor
method for the totalShares field, but you can now add a getTotalShares method
to the Stock class:
// returns the total shares purchased of this stock
public int getTotalShares() {
return totalShares;
}
Here is a corrected version of the payDividend
method that uses the
getTotalShares method from Stock :
// records a dividend of the given amount per share
public void payDividend(double amountPerShare) {
dividends += amountPerShare * getTotalShares();
}
The DividendStock subclass is allowed to call the public getTotalShares
method, so the code now behaves properly. If we had a similar situation in which
subclasses needed to modify total shares from a stock, the Stock class would need to
provide a setTotalShares method or something similar.
Calling a Superclass's Constructor
Unlike other behaviors, constructors are not inherited. You'll have to write your own
constructor for the DividendStock class, and when you do so the problem of the
inability to access private fields will arise again.
The DividendStock constructor should accept the same parameter as the Stock
constructor: the stock symbol. It should have the same behavior as the Stock con-
structor but should also initialize the dividends field to 0.0 . The following con-
structor implementation might seem like a good start, but it is redundant with
Stock 's constructor and won't compile successfully:
// this constructor does not compile
public DividendStock(String symbol) {
this.symbol = symbol;
totalShares = 0;
totalCost = 0.0;
dividends = 0.0; // this line is the new code
}
 
Search WWH ::




Custom Search