A subclass may want to provide a new version
of a method in the superclass. In fact, this is usually the
whole reason for creating a subclass.
When a subclass method matches in name and in the number and type
of arguments to the method in the super-class (that is, the method
signatures match), the subclass is said to override
that method.
In the code below, we see that subclass B
overrides the method doSomething()
in class A:
|
public
class A {
int i = 0;
void doSomething (int k) {
i = k;
}
}
class B extends A {
int j = 0;
void doSomething (ing k) {
j = 10;
i = 2 * k;
}
}
|
When we create an instance of class B,
an invocation of the method doSomething()
will result in a call to the doSomething()
code in class B
rather than A:
...
B b = new B (); //Create an instance
of class B
b.doSomething (); // Access class B method
// doSomething() will be
// called.
...
|
The real power of overriding, however, is illustrated
by this code:
...
A ab = new B (); // Create an instance of
class B
//
but use A type reference.
ab.doSomething ();// Though
the A type reference
// is used, the class B method
// doSomething() will be called.
...
|
Here we see that even though the superclass type
variable ab
references the subclass object, the subclass's method will
be executed rather than the superclass's overridden method.
This is very useful when, for example, an array of the base class
type contains references to various subclasses. Looping through
the array and calling a method that is overriden will result in
the method in the subclass being called rather than the method in
the super-class.
The following code illustrates this so-called polymorphic
feature of object oriented languages:
...
A [] a = new A[4]; // Class A type array
a[0] =new B (); // Create
an instance of class B
// but use A type reference.
a[1] =new B ();
a[2] =new C (); // Where
class C is a subclass
// of class A or B.
for (int i=0; i < 4; i++) {
a[i].doSomething ();// Though
the A type reference
// is used, the overriding
// doSomething () of the
// referenced object
will be
// called.
}
...
|
It is important to understand that even though the
array is of the subclass A,
the code used for the doSomething()
methods will be that of the actual object that is referenced,
not the code for the doSomething()
method in the A
base class .
Latest update: Oct.24, 2004
|