Java Reference
In-Depth Information
Display 8.3
Late Binding Demonstration
1
/**
2
Demonstrates late binding.
3
*/
4
public class
LateBindingDemo
5 {
6
public static void
main(String[] args)
7 {
8 Sale simple =
new
Sale("floor mat", 10.00
);
//One item at $10.00.
9 DiscountSale discount =
new
DiscountSale("floor mat", 11.00,
10 10);
//One item at $11.00 with a 10% discount.
11 System.out.println(simple);
12 System.out.println(discount);
The method
lessThan
uses different
definitions for
discount.bill()
and
simple.bill().
13
if
(discount.lessThan(simple))
14 System.out.println("Discounted item is cheaper.");
15
else
16 System.out.println("Discounted item is not cheaper.");
17 Sale regularPrice =
new
Sale("cup holder", 9.90);
//One item at $9.90.
18
DiscountSale specialPrice =
new
DiscountSale("cup holder",
11.00,10);
19
//One item at $11.00 with a 10% discount.
20 System.out.println(regularPrice);
21 System.out.println(specialPrice);
The method
equalDeals
uses different definitions for
specialPrice.bill()
and
regularPrice.
bill().
22
if
(specialPrice.equalDeals(regularPrice))
23 System.out.println("Deals are equal.");
24
else
25 System.out.println("Deals are not equal.");
26 }
27 }
The
equalDeals
method says that two items are equal provided they have
the same name and the same bill (same total cost). It does not matter how the
bill (the total cost) is calculated.
Sample Dialogue
floor mat Price and total cost = $10.0
floor mat Price = $11.0 Discount = 10.0%
Total cost = $9.9
Discounted item is cheaper.
cup holder Price and total cost = $9.9
cup holder Price = $11.0 Discount = 10.0%
Total cost = $9.9
Deals are equal