Java Reference
In-Depth Information
10.1 Late Binding
Often, the type of a reference variable matches the class of the object to which it
refers exactly. For example, consider the following reference:
ChessPiece bishop;
The bishop variable may be used to point to an object that is created by instan-
tiating the ChessPiece class. However, it doesn't have to. The variable type and
the object it refers to must be compatible, but their types need not be exactly the
same. The relationship between a reference variable and the object it refers to is
more flexible than that.
The term polymorphism can be defined as “having many forms.”
A polymorphic reference is a reference variable that can refer to
different types of objects at different points in time. The specific
method invoked through a polymorphic reference can change from
one invocation to the next.
Consider the following line of code:
KEY CONCEPT
A polymorphic reference can refer to
different types of objects over time.
obj.doIt();
If the reference obj is polymorphic, it can refer to different types of objects at
different times. So if that line of code is in a loop, or if it's in a method that is
called more than once, that line of code could call a different version of the doIt
method each time it is invoked.
At some point, the commitment is made to execute certain code to carry
out a method invocation. This commitment is referred to as binding a method
invocation to a method definition. In many situations, the binding of a method
invocation to a method definition can occur at compile time. For polymor-
phic references, however, the decision cannot be made until run time. The
method definition that is used is based on the object that is being referred to
by the reference variable at that moment. This deferred commit-
ment is called late binding or dynamic binding. It is less efficient
than binding at compile time, because the decision must be made
during the execution of the program. This overhead is generally
acceptable in light of the flexibility that a polymorphic reference
provides.
We can create a polymorphic reference in Java in two ways: using inheritance
and using interfaces. Let's look at each in turn.
KEY CONCEPT
The binding of a method invocation
to its definition is performed at run
time for a polymorphic reference.
 
Search WWH ::




Custom Search