Java Reference
In-Depth Information
This definition of println was given before the class Sale was defined. Yet in the
invocation
System.out.println(aSale);
with an argument aSale of type Sale (and hence also of type Object ), it is the
definition of toString in the class Sale that is used, not the definition of toString in
the class Object . Late binding is what makes this work.
PITFALL: No Late Binding for Static Methods
Java does not use late binding with private methods, methods marked final , or static
methods. With private methods and final methods, this is not an issue because
dynamic binding would serve no purpose anyway. However, with static methods it
can make a difference when the static method is invoked using a calling object. Such
cases arise more often than you might think.
When Java (or any language) does not use late binding, it uses static binding .
With static binding, the decision of which defi nition of a method to use with a calling
object is made at compile time based on the type of the variable naming the object.
Display 8.4 illustrates the effect of static binding on a static method with a
calling object. Note that the static method announcement() in the class Sale
has its definition overridden in the derived class DiscountSale . However, when
an object of type DiscountSale is named by a variable of type Sale , it is the
definition announcement() in the class Sale that is used, not the definition of
announcement in the class DiscountSale .
“So, what's the big deal?” you may ask. A static method is normally called with a
class name and not a calling object. It may look that way, but there are cases where
a static method has a calling object in an inconspicuous way. If you invoke a static
method within the defi nition of a nonstatic method but without any class name or
calling object, then the calling object is an implicit this , which is a calling object.
For example, suppose you add the following method to the class Sale :
static binding
public void showAdvertisement()
{
announcement();
System.out.println(toString( ));
}
Suppose further that the method showAdvertisement is not overridden in the
class DiscountSale , then the method showAdvertisement is inherited unchanged
from Sale .
 
Search WWH ::




Custom Search