Java Reference
In-Depth Information
because the getSalary method has overridden the one from the superclass, meaning
that the code that follows calls itself infinitely:
// flawed implementation of LegalSecretary salary code
public double getSalary() {
return getSalary() + 5000;
}
You also can't just call the Employee version of getSalary by writing
Employee.getSalary() , because that is the syntax for executing static methods, not
instance methods of objects. Instead, Java provides a keyword super that refers to a
class's superclass. This keyword is used when calling a superclass method or con-
structor. Here is the general syntax for calling an overridden method using the super
keyword:
super.<method name>(<expression>, <expression>, ..., <expression>)
The correct version of the legal secretary's salary code is the following. Writing
the marketer's version is left as an exercise.
// working LegalSecretary salary code
public double getSalary() {
return super.getSalary() + 5000; // $5k more than general employees
}
Accessing Inherited Fields
To examine the interactions of more complex classes in a hierarchy, let's shift to a
more complex example than the employee classes we've been using so far. In
Chapter 8's case study, we built a Stock class representing purchased shares of a
given stock. Here's the code for that class, which has been shortened a bit for this
section by removing tests for illegal arguments:
1 // A Stock object represents purchases of shares of a stock.
2 public class Stock {
3
private String symbol;
4
private int totalShares;
5
private double totalCost;
6
7 // initializes a new Stock with no shares purchased
8 public Stock(String symbol) {
9 this .symbol = symbol;
10 totalShares = 0;
11 totalCost = 0.0;
12 }
 
Search WWH ::




Custom Search