Information Technology Reference
In-Depth Information
2.4.2 Overriding
We have said that inheritance permits a class to inherit the characteristics of some
other class. What happens, though if we need to modify some inherited method
within a subclass? Overriding is the practice of replacing a method inherited from
a superclass with a newly defined method in the sub class. Unlike overloading,
which differentiates different implementations of methods with the same name by
unique signatures, overriding requires that a method have exactly the same sig-
nature and return type as the method it is replacing. The following Java code
segment illustrates the use of overriding on two classes related by inheritance.
In the example above, class B , which uses the Java extends keyword to
inherit the structure of class A , requires a different implementation of the
greetings method. Thus, the method is overridden by coding a new method
with an identical signature as the inherited method.
Overriding can be extremely useful, but it carries with it significant risks.
Overriding can potentially negate the integrity that is provided by the use of
inheritance. This occurs when the dependencies within a class are disturbed.
Consider the example in Fig. 2.4 , which illustrates the subclass employee of the
class person . Assume that the setDateOfBirth method defined in the
person class accepts some month-day-year style argument as a date of birth.
Overriding allows us to redefine this method in the employee class to accept a
day-month-year style date of birth. However, the calculateAge method, which
returns an age based on the current date and the dateOfBirth attribute, will
now produce an error unless it too is overridden.
2.4.3 Polymorphism
Imagine for a moment that the only vehicle you had ever driven was a compact
sedan. This is the vehicle that you used when learning to drive, and the only
Search WWH ::




Custom Search