Java Reference
In-Depth Information
memory. Instead, you must precisely identify which withdraw method you want
to call.
Another common error is to forget to call the superclass method altogether. Then
the functionality of the superclass mysteriously vanishes.
450
451
10.4 Subclass Construction
In this section, we discuss the implementation of constructors in subclasses. As an
example, let us define a constructor to set the initial balance of a checking account.
We want to invoke the BankAccount constructor to set the balance to the initial
balance. There is a special instruction to call the superclass constructor from a
subclass constructor. You use the keyword super , followed by the construction
parameters in parentheses:
public class CheckingAccount extends BankAccount
{
public CheckingAccount(double initialBalance)
{
// Construct superclass
super(initialBalance);
// Initialize transaction count
transactionCount = 0;
}
. . .
}
When the keyword super is followed by a parenthesis, it indicates a call to the
superclass constructor. When used in this way, the constructor call must be the first
statement of the subclass constructor. If super is followed by a period and a method
name, on the other hand, it indicates a call to a superclass method, as you saw in the
preceding section. Such a call can be made anywhere in any subclass method.
To call the superclass constructor, you use the super keyword in the first statement
of the subclass constructor.
Search WWH ::




Custom Search