Java Reference
In-Depth Information
and D could be direct subclasses of A or they could be indirect subclasses of A by
subclassing B ).
A[] a = new A[3]; // Class A type array with three elements
a[0] = new B (); // Create an instance of class B but use
// an A reference since the array is
// type A.
a[1] = new C (); // Ditto for C
a[2] = new D (); // And D
for (int i=0; i < 3; i++) {// Call doSomething() for each
// element of the A array.
a[i].doSomething (); // Though the A type reference is used,
// the overriding doSomething() method
// of the actual referenced object is
// invoked.
}
It is important to understand that even though the array type is that of the super-
class A , the code used for the doSomething() methods is that of the actual
object that is referenced in each array element, not the code for the method in the
A base class.
4.2.2 Overriding versus overloading
It is important to note how overriding differs from overloading . The latter refers
to reusing the same method name but with a different parameter list and was
explained in Chapter 3. Briefly, if a class contains two (or more) methods of the
same name but with different parameter lists, all those methods are said to be
overloaded. The compiler automatically decides which method to call based on
the parameters used when the method is invoked. What was not mentioned in
Chapter 3 is that overloading can occur across inherited classes. If a subclass
reuses a method name from a parent class but changes the parameter list, then
the method is still overloaded, just as if both methods appeared in the same class.
(Note that via inheritance both methods really do appear in the subclass; the
fact that the source code appears in two different places makes no difference.) In
over loading , the new method does not replace the superclass method; it just reuses
the name with a different parameter list. Calling the method with the original
parameter list invokes the original method; calling it with the new parameter list
invokes the new method.
Confusing overriding and overloading is a vexing error, both for novices and
experienced Java developers. If a subclass attempts to override a method in a
 
Search WWH ::




Custom Search