Array of Goods Objects

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:

  • Could these 4 objects be kept in an array?
    • Yes.
  • What would the array type be?
    • Goods[]

Array of Goods Objects

Here is a modified testing program that uses an array:

public class Store
{

  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, "Austin" );
    inventory[3] = new Toy  ( "Leggos", 54.45, 8 );

    inventory[0].display();
    inventory[1].display();
    inventory[2].display();
    inventory[3].display();
  }
}

Since each child class is-a Goods, an array of type Goods[] can be used with any of them. The array inventory has 10 slots, but the program uses only 4 of them, like this:

array picture

As always, each slot of the array is a reference variable which can refer to an object that has been created with a new.

QUESTION 16:

Is each of the classes Toy and Book taxable?