Java Reference
In-Depth Information
Inheriting and overriding
A subclass inherits all the components of the superclass. This means that each
instance of the subclass contains all the instance components of the superclass.
The folder in Fig. 4.2 makes this clear.
Suppose a variable b contains the name a7 of the folder in Fig. 4.2 (later, we
see how to create the folder and store its name in b ). Then, method getName in
the folder can be called using the expression
This expression evaluates to the string "Gries" . This expression calls an inher-
ited method. In the same way, method getBonus in the folder can be called using
There are two instance functions getCompensation in folder a7 . Which one
does the expression
call? It calls the method that is declared in subclass Executive. We say that
method getCompensation in class Executive overrides the inherited method.
Comparing the two methods, we can see that this makes sense. Since the
/** An executive: an employee with a bonus. */
public class Executive extends Employee {
/** Yearly bonus */
private double bonus;
/** Constructor: a person with name n , year hired d , salary 50,000 , and bonus b */
public Executive(String n, int d, double b) {
super (n, d);
bonus= b;
/** = this executive's bonus */
public double getBonus()
{ return bonus; }
/** = this executive's yearly compensation */
public double getCompensation()
{ return super .getCompensation() + bonus; }
/** = a representation of this executive */
public String toString()
{ return super .toString() + ", bonus " + bonus; }
Figure 4.1:
Subclass Executive
Search WWH ::

Custom Search