Java Reference
In-Depth Information
Overriding a Method Definition
The definition of an inherited method can be changed in the definition of a derived
class so that it has a meaning in the derived class that is different from what it is in the
base class. This is called overriding the definition of the inherited method. For exam-
ple, the methods toString and equals are overridden (redefined) in the definition of
the derived class HourlyEmployee . They are also overridden in the class Salaried-
Employee . To override a method definition, simply give the new definition of the
method in the class definition, just as you would with a method that is added in the
derived class.
overriding
Overriding a Method Definition
A derived class inherits methods that belong to the base class. However, if a derived class
requires a different definition for an inherited method, the method may be redefined in the
derived class. This is called overriding the method definition.
The final Modifier
If you add the modifier final to the definition of a method, that indicates that the method
may not be redefined in a derived class. If you add the modifier final to the definition of a
class, that indicates that the class may not be used as a base class to derive other classes.
We will say more about the final modifier in Chapter 8.
Changing the Return Type of an Overridden Method
In a derived class, you can override (change) the definition of a method from the base
class. As a general rule, when overriding a method definition, you may not change the
type returned by the method, and you may not change a void method to a method
that returns a value, nor a method that returns a value to a void method. The one
exception to this rule is: If the returned type is a class type, then you may change the
returned type to that of any descendent class of the returned type. For example, if a
function returns the type Employee (Display 7.2), when you override the function def-
inition in a derived class, you may change the returned type to HourlyEmployee (Dis-
play 7.3), SalariedEmployee (Display 7.5), or any other descendent class of the class
Employee . This sort of changed return type is known as a covariant return type and is
new in Java version 5.0; it was not allowed in earlier versions of Java. Earlier versions
of Java allowed absolutely no changes to the returned type. We will give complete
examples of changing the returned type of an overridden method in Chapter 8. Here
we will just outline an example.
covariant
return type
Search WWH ::




Custom Search