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

Answer:


Array of Goods Objects

array picture
public class StoreArray
{

  public static void main ( String[] args )
  {
    Goods[] inventory =  new Goods[10];
    inventory[0] = new Goods( "bubble bath", 1.40 );
    inventory[1] = new Food ( "ox tails", 4.45, 1500 );
    inventory[2] = new Book ( "Emma", 24.95, "Austen" );
    inventory[3] = new Toy  ( "Leggos", 54.45, 8 );

    System.out.println( inventory[0] );
    System.out.println( inventory[1] ); 
    System.out.println( inventory[2] );
    System.out.println( inventory[3] );
  }
}

The modified testing program uses an array.

Since each child class is-a Goods, an array of type Goods[] can be used for any of them. This is polymorphism, now used with each cell. The array inventory has 10 cells, but the program uses only 4 of them.

Each cell of the array is a reference variable which can refer to an object of type Goods or to any derived class of Goods.

Here is the output of the program:

item: bubble bath price: 1.4
item: ox tails price: 4.45,  1500.0 calories
item: Emma price: 24.95, author: Austen
item: Leggos price: 54.45,  minimum age: 8

QUESTION 19:

(Review:) Does this line:

System.out.println( inventory[1] );

execute the same toString() method as this line:

System.out.println( inventory[2] );

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