No.
This line:
System.out.println( inventory[1] );
executes the toString()
method for a Food
object. But this line:
System.out.println( inventory[2] );
executes the toString()
method for a Book
object.
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 Taxable
interface tells the compilder that all Taxable
objects will have a calculateTax()
method,
so that method can be used with these variables.
Would the following work?
System.out.println( item1.toString() ); System.out.println( item2.toString() );