Java Reference
In-Depth Information
Self-Test Exercises
1. Explain the difference between the terms late binding and polymorphism .
2. Suppose you modify the definitions of the class Sale ( Display 8.1 ) by adding the
modifier final to the definition of the method bill . How would that change
the output of the program in Display 8.3 ?
3. Would it be legal to add the following method definition to the class
DiscountSale ?
public static boolean isAGoodBuy(Sale theSale)
{
return (theSale.getDiscount() > 20);
}
4. Complete the definition of the method equals for the class DiscountSale
( Display 8.2 ).
Late Binding with toString
In the subsection “The Methods equals and toString ” in Chapter 4 , we noted that if
you include an appropriate toString method in the definition of a class, then you can
output an object of the class using System.out.println. For example, the following
works because Sale has a suitable toString method:
Sale aSale = new Sale("tire gauge", 9.95);
System.out.println(aSale);
This produces the following screen output:
tire gauge Price and total cost = $9.95
This happens because Java uses late binding. We explain this here.
The method invocation System.out.println(aSale) is an invocation of the
method println with the calling object System.out. One definition of the method
println has a single argument of type Object . The definition is equivalent to the
following:
public void println(Object theObject)
{
System.out.println(theObject.toString());
}
(The invocation of the method println inside the braces is a different, overloaded
definition of the method println . That invocation inside the braces uses a method
println that has a parameter of type String , not a parameter of type Object .)
 
Search WWH ::




Custom Search