Java Reference
In-Depth Information
4.2.1 Overriding
A common situation is when a class is needed that provides most of the func-
tionality of a potential superclass except one of the superclass methods doesn't
do quite the right thing. Adding a new method with a different name in a sub-
class doesn't really solve the problem because the original superclass method
remains accessible to users of the subclass, thereby resulting in a source of errors
should a user inadvertently use the original name instead of the new name. What
is really needed is a way to change the behavior of that one superclass method
without having to rewrite the superclass. Often we may not even have the super-
class source code, making rewriting it impossible. Even if we do have the source
code, rewriting it would be the wrong approach. That method in the superclass
is assumed to be completely appropriate for the superclass and should not be
changed. We wish to change the behavior of the method only for instances of our
subclass, retaining the existing behavior for instances of the superclass and other
subclasses that expect the original behavior of the method.
Java provides just this capability in a technique known as overriding .Over-
riding permits a subclass to provide a new version of a method already defined in
a superclass. Instances of the original superclass (and other subclasses) see the
original method. Instances of the overriding subclass see the new (overridden)
method. In fact, overriding is often the whole reason to create a subclass.
Overriding occurs when a subclass method exactly matches the signature (the
method name, return type, and parameter types) of a method in a superclass. If
the return type is different, a compile-time error occurs. If the parameter list is
different, then overloading occurs (already discussed in Chapter 3), not overrid-
ing. In the next section we discuss the differences, which are very important, but
first we give an example of overriding. In the code below, we see that subclass
Child overrides the method doSomething() in class Parent :
public class Parent {
int parent - int = 0;
void doSomething (int i) {
parent - int = i;
}
}
class Child extends Parent {
int child - int = 0;
void doSomething (int i) {
child - int = 10;
parent - int = 2*i;
}
}
 
Search WWH ::




Custom Search