Type Casts

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.

Would the following work?

item1.display() ;

Answer:

No. All the compiler has been told is that item1 implements the methods in the interface Taxable. The display() method is not in the interface.

Type Casts

When you use a variable of type Taxable you are asking to use the "taxable" aspect of the object. Many different kinds of objects might be referred to by the variable. (In a larger program there may be Taxable classes that are not Goods.) The compiler can only use the methods it knows that the object must have—those in the interface

However, you can use a type cast to tell the compiler that in a particular statement in the program the variable will refer to an object of a specific class:

  public static void main ( String[] args )
  {
    Taxable item1 = new Book ( "Emma", 24.95, "Austin" );
    System.out.println( "Tax on item 1 "+ item1.calculateTax() );

    ((Book)item1).display();
  }

This program is not very sensibly written, since if the variable item1 were of type Book everything would work without the need for a type cast. But in programs with more complicated logic such casts are sometimes needed.

QUESTION 18:

Why are the red parentheses needed in:

((Book)item1).display();