Java Reference
In-Depth Information
Before we go any further with the discussion of method overriding, you should
understand the difference between method overriding and method overloading. As
we discussed in Chapter 2 , method overloading refers to the practice of defining
multiple methods (in the same class) that have the same name but different parame‐
ter lists. This is very different from method overriding, so don't get them confused.
Overriding is not hiding
Although Java treats the fields and methods of a class analogously in many ways,
method overriding is not like field hiding at all. You can refer to hidden fields sim‐
ply by casting an object to an instance of the appropriate superclass, but you cannot
invoke overridden instance methods with this technique. The following code illus‐
trates this crucial difference:
class A { // Define a class named A
int i = 1 ; // An instance field
int f () { return i ; } // An instance method
static char g () { return 'A' ; } // A class method
}
class B extends A { // Define a subclass of A
int i = 2 ; // Hides field i in class A
int f () { return - i ; } // Overrides method f in class A
static char g () { return 'B' ; } // Hides class method g() in class A
}
public class OverrideTest {
public static void main ( String args []) {
B b = new B (); // Creates a new object of type B
System . out . println ( b . i ); // Refers to B.i; prints 2
System . out . println ( b . f ()); // Refers to B.f(); prints -2
System . out . println ( b . g ()); // Refers to B.g(); prints B
System . out . println ( B . g ()); // A better way to invoke B.g()
A a = ( A ) b ; // Casts b to an instance of class A
System . out . println ( a . i ); // Now refers to A.i; prints 1
System . out . println ( a . f ()); // Still refers to B.f(); prints -2
System . out . println ( a . g ()); // Refers to A.g(); prints A
System . out . println ( A . g ()); // A better way to invoke A.g()
}
}
While this difference between method overriding and field hiding may seem sur‐
prising at first, a little thought makes the purpose clear.
Suppose we are manipulating a bunch of Circle and Ellipse objects. To keep track
of the circles and ellipses, we store them in an array of type Circle[] . We can do
this because Ellipse is a subclass of Circle , so all Ellipse objects are legal Circle
objects.
Search WWH ::




Custom Search