Java Reference
In-Depth Information
4.1.8 overriding a method
Methods in the base class are overridden in the derived class by simply pro-
viding a derived class method with the same signature. 3 The derived class
method must have the same return type and may not add exceptions to the
throws list. 4 The derived class may not reduce visibility, as that would violate
the spirit of an IS-A relationship. Thus you may not override a public method
with a package-visible method.
Sometimes the derived class method wants to invoke the base class
method. Typically, this is known as partial overriding . That is, we want to do
what the base class does, plus a little more, rather than doing something
entirely different. Calls to a base class method can be accomplished by using
super . Here is an example:
The derived class
method must have
the same return
type and signature
and may not add
exceptions to the
throws list.
Partial overriding
involves calling a
base class method
by using super .
public class Workaholic extends Worker
{
public void doWork( )
{
super.doWork( ); // Work like a Worker
drinkCoffee( ); // Take a break
super.doWork( ); // Work like a Worker some more
}
}
A more typical example is the overriding of standard methods, such as
toString . Figure 4.8 illustrates this use in the Student and Employee classes.
4.1.9 type compatibility revisited
Figure 4.9 illustrates the typical use of polymorphism with arrays. At line 17,
we create an array of four Person references, which will each be initialized to
null . The values of these references can be set at lines 19 to 24, and we know
that all the assignments are legal because of the ability of a base type refer-
ence to refer to objects of a derived type.
The printAll routine simply steps through the array and calls the toString
method, using dynamic dispatch. The test at line 7 is important because, as we
have seen, some of the array references could be null .
3. If a different signature is used, you simply have overloaded the method, and now there are
two methods with different signatures available for the compiler to choose from.
4. Java 5 loosens this requirement and allows the return type of the derived class's method to
be slightly different as long as it is “compatible.” The new rule is discussed in Section
4.1.11.
 
 
Search WWH ::




Custom Search