go to previous page   go to home page   go to next page

Answer:

No.

This line:

inventory[1].display();

executes the display() method for a Food object. But this line:

inventory[2].display();

executes the display() method for a Book object.

The class of the object determines which method is executed, not the type of the reference variable.


Interface as a Type

public class Store
{
  public static void main ( String[] args )
  {
    Taxable item1 = new Book ( "Emma", 24.95, "Austen" );
    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() );

  }
}

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:

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 19:

Would the following work?

item1.display() ;