Java Reference
In-Depth Information
PITFALL: (continued)
Now consider the following code:
Sale s =
new
Sale("floor mat", 10.00);
DiscountSale discount =
new
DiscountSale("floor mat", 11.00,10);
s.showAdertisement();
discount.showAdertisement();
You might expect the following output:
This is the Sale class.
floor mat Price and total cost = $10.0
This is the DiscountSale class.
floor mat Price = $11.0 Discount = 10.0%
Total cost = $9.9
However, because the defi nition used for the static method
announcement
, inside of
showAdvertisement
, is determined at compile time (based on the type of the variable
holding the calling object), the output actually is the following, where the change is
shown in blue:
This is the Sale class.
floor mat Price and total cost = $10.0
This is the
Sale
class.
floor mat Price = $11.0 Discount = 10.0%
Total cost = $9.9
Java uses late binding with the nonstatic method
toString
but static binding with
the static method
announcement
.
■
Downcasting and Upcasting
The following is perfectly legal (given the class definitions in Displays 8.1 and 8.2 ):
Sale saleVariable;
DiscountSale discountVariable =
new
DiscountSale("paint", 15, 10);
saleVariable = discountVariable;
System.out.println(saleVariable.toString());
An object of a derived class (in this case, the derived class
DiscountSale
) also has the
type of its base class (in this case,
Sale
) and so can be assigned to a variable of the base
class type. Now let's consider the invocation of the method
toString()
on the last
line of the preceding code.