Java Reference
In-Depth Information
We can use the version of the method toString() defined in the base class
Employee to simplify the definition of the method toString() in the derived class
HourlyEmployee . The following is an equivalent way to define toString() in the
derived class HourlyEmployee :
public String toString() //in the derived class HourlyEmployee
{
return ( super .toString()
+ "\n$" + wageRate + " per hour for " + hours + " hours");
}
The expression super .toString() is an invocation of the method toString() using
the definition of toString() given in the base class Employee .
You can only use super in this way within the definition of a method in a derived
class. Outside of the definition of the derived class you cannot invoke an overridden
method of the base class using an object of the derived class.
Invoking the Old Version of an Overridden Method?
Within the definition of a method of a derived class, you can invoke the base class version of
an overridden method of the base class by prefacing the method name with super and a dot.
Outside of the derived class definition, there is no way to invoke the base class version of an
overridden method using an object of the derived class.
EXAMPLE
public String toString()
{
return ( super .toString()
+ "\n$" + wageRate + " per hour for " + hours + " hours");
}
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 ances-
tor 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.
Search WWH ::




Custom Search