Java Reference
In-Depth Information
Self-Test Exercises
5. Consider the following code, which is identical to the code discussed earlier in
the opening of the subsection, “Downcasting and Upcasting,” except that we
added the type cast shown in color:
Sale saleVariable;
DiscountSale discountVariable =
new DiscountSale("paint", 15, 10);
saleVariable = (Sale) discountVariable;
System.out.println(saleVariable.toString());
We saw that without the type cast, the defi nition of the toString method used
is the one given in the defi nition of the class DiscountSale . With this added
type cast, will the defi nition of the toString method used still be the one given
in DiscountSale or will it be the one given in the defi nition of Sale ?
6. Would it be legal to add the following method defi nition to the class
DiscountSale ?
What about adding it to the class Sale ?
public static void showDiscount(Sale object)
{
System.out.println("Discount = "
+ object.getDiscount());
}
7 .
What output is produced by the following code?
Sale someObject = new DiscountSale("map", 5, 0);
DiscountSale ds = new DiscountSale();
if (someObject instanceof DiscountSale)
{
ds = (DiscountSale)someObject;
System.out.println("ds was changed to " + someObject);
}
else
System.out.println("ds was not changed.");
Search WWH ::




Custom Search