Java Reference
In-Depth Information
PITFALL: You Cannot Use Multiple
super
s
As we already noted, within the definition of a method of a derived class, you can call
an overridden method of the base class by prefacing the method name with
super
and a dot. However, you cannot repeat the use of
super
to invoke a method from
some ancestor class other than a direct parent. For example, suppose that the class
Employee
were derived from the class
Person
, and the class
HourlyEmployee
is
derived from the class
Employee
. You might think that you can invoke a method of
the class
Person
within the definition of the class
HourlyEmployee
, by using
super.
super
, as in
super
.
super
.toString()
//ILLEGAL!
However, as the comment indicates, it is illegal to have such multiple
super
s in Java.
■
Self-Test Exercises
14. Redefi ne the
toString
method of the class
SalariedEmployee
( Display 7.5 )
so that it uses
super.toString()
. This new defi nition of
toString
will be
equivalent to the one given in Display 7.5.
15. Redefi ne the
equals
method for the class
HourlyEmployee
( Display 7.3 ) using
super.equals
to invoke the
equals
method of the base class
Employee
.
16. Is the following program legal? The relevant classes are defi ned in Displays 7.2
and 7.3 .
public class
EmployeeDemo
{
public static void
main(String[] args)
{
HourlyEmployee joe =
new
HourlyEmployee("Joe Young",
new
Date("Feb", 1, 2004), 10.50, 40);
String nameNDate = joe.
super
.toString();
System.out.println(nameNDate);
}
}
(continued)