Java Reference
In-Depth Information
PITFALL:
(continued)
On the other hand, both the class
Employee
and the class
HourlyEmployee
define a
method with the following method heading:
public
String toString()
In this case, the class
HourlyEmployee
has only one method named
toString()
, but
the definition of the method
toString()
in the class
HourlyEmployee
is different from
the definition of
toString()
in the class
Employee
; the method
toString()
has been
overridden
(that is, redefined).
If you get overriding and overloading confused, you do have one consolation. They
are both legal.
■
The
super
Constructor
You can invoke a constructor of the base class within the definition of a derived class
constructor. A constructor for a derived class uses a constructor from the base class in a
special way. A constructor for the base class normally initializes all the data inherited
from the base class. So a constructor for a derived class begins with an invocation of a
constructor for the base class. The details are as follows:
There is a special syntax for invoking the base class constructor that is illustrated by
the constructor definitions for the class
HourlyEmployee
given in Display 7.3. In what
follows we have reproduced the beginning of one of the constructor definitions for the
class
HourlyEmployee
taken from that display:
public
HourlyEmployee(String theName, Date theDate,
double
theWageRate,
double
theHours)
{
super
(theName, theDate);
if
((theWageRate >= 0) && (theHours >= 0))
{
wageRate = theWageRate;
hours = theHours;
}
else
...
The line
super
super
(theName, theDate);
is a call to a constructor for the base class, which in this case is a call to a constructor
for the class
Employee
.