A type cast is necessary to tell the compiler that the variable tax
in this case contains a reference to a Book
object.
public class Store
{
public static void main ( String[] args )
{
Book book ;
Taxable tax = new Book ( "Emma", 24.95, "Austen" );
book = (Book)tax;
System.out.println( book );
System.out.println( "Tax on item 1 "+ book.calculateTax() );
}
}
Now Consider the following code:
public class Store { public static void main ( String[] args ) { Goods toy ; Taxable tax = new Toy ( "Building Blocks", 1.49, 6 ); toy = tax; System.out.println( toy ); System.out.println( "Tax: "+ toy.calculateTax() ); } }
Are type casts necessary? Where should they go? Hint: there are several correct answers.