Java Reference
In-Depth Information
superclass but doesn't use the exact same parameter list, then the method is really
over
loaded
, not over
ridden
.Weillustrate this with the following example:
public class
Parent
{
int i
=
0;
void doSomething (int k)
{
i
=
k;
}
}
class
Child
extends Parent {
void doSomething (long k) {
i = 2*k;
}
}
Here we created class
Child
with the intention of overriding the
doSomething (int k)
method in
class Parent
but we mistakenly
changed the
int
parameter to a
long
parameter as shown. Then the
Child
version of
doSomething()
has
overloaded
the
Parent
version, not overrid-
den it. Look what happens when we attempt to call
doSomething()
from an
instance of
Child
:
...
Parent p
=
new Parent (); // Create a Parnet instance.
Child c = new Child (); // Create a Child instance.
p.doSomething (5); // The method in Parent is invoked,
// as expected.
c.doSomething (3); // The method in Parent, not Child, is
// invoked, probably not as expected.
The call to
c.doSomething(3)
passes an
int
parameter, not a
long
(a literal
3
is an
int
;tomakeita
long
,an
l
or
L
must be appended, as in
3L
). Therefore the
overloaded method that takes an
int
is invoked, not the
Child
version expected.
Even though we have explicitly asked for
c.doSomething()
, the
int
version
of the method named
doSomething()
gets invoked - again, the fact that the
source code happens to appear in the superclass makes no difference.
This error is often difficult to uncover. It occurs most often when an overridden
superclass method is changed while forgetting to make the same change in the
corresponding overriding subclass methods at the same time.
Search WWH ::
Custom Search