Here is one correct answer:
public class Store { public static void main ( String[] args ) { Goods toy ; Taxable tax = new Toy ( "Building Blocks", 1.49, 6 ); toy = (Toy)tax; toy.display(); System.out.println( "Tax: "+ ((Taxable)toy).calculateTax() ); } }
The first type cast in the answer must cast tax
to a type
Goods
(or an ancestor).
The second must cast toy
to Taxable
or to
a class that implements Taxable
.
When you think about such problems, remember that at compile time objects do not exist. The compiler knows what methods are available with a reference variable based only on the type of the variable.
For example, in the above,
only the calculateTax()
method and methods of Object
are available with tax
.
At run time the object tax
happens to point to has more methods avaialble.
To say this in the code, use a type cast.
You might complain that it is obvious in this program that toy
points to an object with a calculateTax()
method.
But with more complicated programs it is not obvious.
It would be disasterous if the the compiler did one thing for obvious situations,
and another for non-obvious.
Here is another possible answer:
public class Store { public static void main ( String[] args ) { Goods toy ; Taxable tax = new Toy ( "Building Blocks", 1.49, 6 ); toy = (Goods)tax; System.out.println( toy ); System.out.println( "Tax: "+ ((Toy)toy).calculateTax() ); } }
Is this answer correct?