When is a Type Cast Needed?

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
((Book)item1).display();

Answer:

Because you want to:

  • First, cast item1 to type Book.
  • Then, invoke the display() method that objects of type Book have.

When is a Type Cast Needed?

Now examine the following:

  public static void main ( String[] args )
  {
    Book    book ;
    Taxable tax = new Book ( "Emma", 24.95, "Austin" );

    book = tax;
    book.display();
    System.out.println( "Tax on item 1 "+ book.calculateTax() );
  }

QUESTION 19:

Is a type cast necessary? Where should it go?