Java Reference
In-Depth Information
When we have an instance of class Child ,aninvocation of the method
doSomething() results in a call to the overridden doSomething() code
in class Child rather than Parent :
...
Parent p = new Parent (); // Create instance of class Parent
Child c = new Child (); // Create instance of class Child
c.doSomething (5); // The method in class Child is invoked.
p.doSomething (3); // The method in class Parent is invoked.
On the other hand, if we call the doSomething() method on a Parent
instance, then the original doSomething() code from class Parent is invoked.
Java automatically invokes the correct method based on the type of the object
reference.
The real power of overriding, however, is illustrated by this code:
...
Parent p = new Child (); // Create an instance of Child
// but use a Parent type reference.
p.doSomething (); // Though the Parent type reference
// is used, the Child class's doSomething()
// is executed.
...
This code has created an instance of class Child but declared it to be of
type Parent . Doing so is legal when Child is a subclass of Parent , since
Child has all the methods and data of type Parent .Even though the vari-
able p is declared to be the superclass type, it actually references the sub-
class object. So the subclass method is executed rather than the method in the
superclass. This happens because the instance p really is of type Child , not
type Parent . The actual type of the object referred to by an object reference
is the type that it is “born as,” not the type of variable that holds the object
reference.
This feature is very useful when, for example, the elements of an array of
the base class type contain references to instances of various subclasses. Looping
through the array and calling a method that is overridden will result in the method
in the subclass being called rather than the method in the base class.
The following code illustrates this so-called polymorphic feature of object-
oriented languages. We begin with a superclass named A and three subclasses B ,
C , and D , all of which override the doSomething() method from A (classes C
Search WWH ::




Custom Search