Interface as a Type

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.

Answer:

Yes.

Interface as a Type

An interface can be used as a data type for a reference variable. Since Toy and Book implement Taxable, they can both be used with a reference variable of type Taxable:

  public static void main ( String[] args )
  {
    Taxable item1 = new Book ( "Emma", 24.95, "Austin" );
    Taxable item2 = new Toy  ( "Leggos", 54.45, 8 );

    System.out.println( "Tax on item 1 "+ item1.calculateTax() );
    System.out.println( "Tax on item 2 "+ item2.calculateTax() );

  }

The compiler has been told in the interface that all Taxable objects will have a calculateTax() method, so that method can be used with the variables.

QUESTION 17:

Would the following work?

item1.display() ;