Java Reference
In-Depth Information
Because Java uses late binding, the invocation
saleVariable.toString()
uses the definition of the method
toString
given in the class
DiscountSale
. So the
output is
paint Price = $15.0 Discount = 10.0%
Total cost = $13.5
Because of late binding, the meaning of the method
toString
is determined by the
object, not by the type of the variable
saleVariable
.
You may well respond, “Who cares? Why would I ever want to assign an object of
type
DiscountSale
to a variable of type
Sale
?”
1
You make such assignments more
often than you might think, but you tend to not notice them because they happen
behind the scenes. Recall that a parameter is really a local variable, so every time
you use an argument of type
DiscountSale
for a parameter of type
Sale
, you are
assigning an object of type
DiscountSale
to a variable of type
Sale
. For example,
consider the following invocation taken from the definition of the copy constructor for
DiscountSale
( Display 8.2 ):
super
(originalObject);
In this invocation,
originalObject
is of type
DiscountSale
, but
super
is the copy
constructor for the base class
Sale
. Therefore,
super
has a parameter of type
Sale
,
which is a local variable of type
Sale
that is set equal to the argument
originalObject
of type
DiscountSale
.
Note that the type of the variable naming an object determines which method
names can be used in an invocation with that calling object. (Self-Test Exercise 3 may
help you to understand this point.) However, the object itself always determines the
meaning of a method invocation performed by an object; this is what we mean by
late binding
.
An Object Knows the Definitions of Its Methods
The type of a class variable determines which method names can be used with the variable,
but the object named by the variable determines which definition of the method name is
used. A special case of this rule is the following: The type of a class parameter determines
which method names can be used with the parameter, but the argument determines which
definition of the method name is used.
1
It is actually the references to the object that are assigned, not the objects themselves, but that subtlety
is not relevant to what we are discussing here, and the language is already complicated enough.