Java Reference
In-Depth Information
The single isOlder routine can be used for all of the following calls:
isOlder(p,p) , isOlder(s,s) , isOlder(e,e) , isOlder(p,e) , isOlder(p,s) ,
isOlder(s,p) , isOlder(s,e) , isOlder(e,p) , isOlder(e,s) .
All in all, we now have leveraged one non-class routine to work for nine dif-
ferent cases. In fact there is no limit to the amount of reuse this gets us. As soon as
we use inheritance to add a fourth class into the hierarchy, we now have 4 times 4,
or 16 different methods, without changing isOlder at all! The reuse is even more
significant if a method were to take three Person references as parameters. And
imagine the huge code reuse if a method takes an array of Person references.
Thus, for many people, the type compatibility of derived classes with their
base classes is the most important thing about inheritance because it leads to
massive indirect code reuse . And as isOlder illustrates, it also makes it very
easy to add in new types that automatically work with existing methods.
4.1.3 dynamic dispatch and polymorphism
There is the issue of overriding methods: If the type of the reference and the
class of the object being referenced (in the example above, these are Person
and Student , respectively) disagree, and they have different implementations,
whose implementation is to be used?
As an example, consider the following fragment:
Student s = new Student( "Joe", 26, "1 Main St",
"202-555-1212", 4.0 );
Employee e = new Employee( "Boss", 42, "4 Main St.",
"203-555-1212", 100000.0 );
Person p = null;
if( getTodaysDay( ).equals( "Tuesday" ) )
p = s;
else
p = e;
System.out.println( "Person is " + p.toString( ) );
A polymorphic vari-
able can reference
objects of several
different types.
When operations
are applied to the
polymorphic vari-
able, the operation
appropriate to the
referenced object
is automatically
selected.
Here the static type of p is Person . When we run the program, the dynamic
type (i.e., the type of the object actually being referenced) will be either
Student or Employee . It is impossible to deduce the dynamic type until the
program runs. Naturally, however, we would want the dynamic type to be
used, and that is what happens in Java. When this code fragment is run, the
toString method that is used will be the one appropriate for the dynamic type
of the controlling object reference.
This is an important object-oriented principle known as polymorphism .
A reference variable that is polymorphic can reference objects of several
different types. When operations are applied to the reference, the operation
that is appropriate to the actual referenced object is automatically selected.
 
Search WWH ::




Custom Search