This exercise will give you practice in composing objects out of other objects. First you will define the Jam class. Objects of this class represent jars of fruit preserves. Then several these jars will be placed in a Pantry.
You may have some doubts that this is a sensible program. Perhaps it would be a good idea to have the spread() method print out a message each time it is used.
7. Design of the Pantry class. Let us say that a pantry consists of three jars of jam of any type and size. The methods of a pantry will be to:
Entire Program, with testing class: You might wish to copy this program to NotePad, save it to a file, and to play with it.
class Jam
{
// Instance Variables
String contents ; // type of fruit in the jar
String date ; // date of canning
int capacity ; // amount of jam in the jar
// Constructors
Jam( String contents, String date, int size )
{
this . contents = contents ;
this . date = date ;
capacity = size;
}
// Methods
public boolean empty ()
{
return ( capacity== 0 ) ;
}
public void print ()
{
System.out.println ( contents + " " + date + " " + capacity + " fl. oz." ) ;
}
public void spread ( int fluidOz)
{
if ( !empty() )
{
if ( fluidOz <= capacity )
{
System.out.println("Spreading " + fluidOz + " fluid ounces of "
+ contents );
capacity = capacity - fluidOz ;
}
else
{
System.out.println("Spreading " + capacity + " fluid ounces of "
+ contents );
capacity = 0 ;
}
}
else
System.out.println("No jam in the Jar!");
}
}
class Pantry
{
// Instance Variables
private Jam jar1 ;
private Jam jar2 ;
private Jam jar3 ;
private Jam selected ;
// Constructors
Pantry( Jam jar1, Jam jar2, Jam jar3 )
{
this . jar1 = jar1 ;
this . jar2 = jar2 ;
this . jar3 = jar3 ;
selected = null ;
}
// Methods
public void print()
{
System.out.print("1: "); jar1 . print() ;
System.out.print("2: "); jar2 . print() ;
System.out.print("3: "); jar3 . print() ;
}
// assume that the user entered a correct selection, 1, 2, or 3
public void select( int jarNumber )
{
if ( jarNumber == 1 )
selected = jar1 ;
else if ( jarNumber == 2 )
selected = jar2 ;
else
selected = jar3 ;
}
// spread the selected jam
public void spread( int oz )
{
selected . spread( oz ) ;
}
}
class PantryTester
{
public static void main ( String[] args )
{
Jam goose = new Jam( "Gooseberry", "7/4/86", 12 );
Jam apple = new Jam( "Crab Apple", "9/30/99", 8 );
Jam rhub = new Jam( "Rhubarb", "10/31/99", 3 );
Pantry hubbard = new Pantry( goose, apple, rhub );
hubbard.print();
hubbard.select(1);
hubbard.spread(2);
hubbard.print();
hubbard.select(3);
hubbard.spread(4);
hubbard.print();
}
}
When you run the program you will be rewarded with the output:
1: Gooseberry 7/4/86 12 fl. oz. 2: Crab Apple 9/30/99 8 fl. oz. 3: Rhubarb 10/31/99 3 fl. oz. Spreading 2 fluid ounces of Gooseberry 1: Gooseberry 7/4/86 10 fl. oz. 2: Crab Apple 9/30/99 8 fl. oz. 3: Rhubarb 10/31/99 3 fl. oz. Spreading 3 fluid ounces of Rhubarb 1: Gooseberry 7/4/86 10 fl. oz. 2: Crab Apple 9/30/99 8 fl. oz. 3: Rhubarb 10/31/99 0 fl. oz.