Computing Concepts with Java Essentials
Laboratory Notebook
Chapter 8 - Classes

Cay S. Horstmann
Geof Pawlicki

Your name:
Your email address:
Your student ID number:

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.


Lab Objectives

To gain experience with


R1. Discovering classes

In each of the following examples, locate and describe those conceptually related procedures and data elements that can be combined into a single class.

/* Program to calculate the optimum price for theater ticket 
   based on data from preview showings in different cities
*/

import ccj.*;
         
public class OptPrice
{  public static void main(String[] args)
   {  boolean more = true;
      String answer = "";
      int numberSold = 0;
      int bestNumber = 0;
      double unitPrice = 0.0;
      double bestPrice = 0.0;
      String city = "";
      String bestCity = "";   

      while (more)
      {  System.out.print("Number sold: ");
         numberSold = Console.in.readInt();;

         System.out.print("Unit Price: ");
         unitPrice = Console.in.readDouble();

         System.out.print("City : ");
         city = Console.in.readWord();

         if (( numberSold * unitPrice) > (bestNumber * bestPrice))
         {   bestNumber = numberSold;
             bestPrice = unitPrice;
             bestCity = city;
         }

         System.out.print("More data (Y/N)? ");
         answer = Console.in.readWord();
         if (!answer.toUpperCase().equals("Y")) 
         {   more = false;
         }
      }

      System.out.println(bestNumber * bestPrice +
         " dollars generated on sale of " +
         bestNumber + " tickets at " + bestPrice +
         " per ticket in " + bestCity);
   }
}
/*  program to record general patient information before a physical examination
*/

import ccj.*;

public class VitalSign

{  public static int pulse()
   {   return Numeric.randomInt(LO, HI);
   }

   public static int thermometer()
   {   return Numeric.randomInt(LO, HI);
   }

   public static int diastolicBloodPressure()
   {   return Numeric.randomInt(LO, HI);
   }

   public static int systolicBloodPressure()
   {   return Numeric.randomInt(LO, HI);
   }

   public static void printChart(String name,
      int age, String ssn, int diastolic, int systolic,
      int temperature, int pulseRate)
   {  System.out.println("Name " + " " + name + "\n" +
         "Age " + " " + age + "\n" +
         "SSN: " + " " + ssn + "\n" +
         "Diastolic: " + " " + diastolic + "\n" +
         "Systolic: " + " " + systolic + "\n" +
         "Temperature: " + " " + temperature + "\n" +
         "Pulse rate: " + " " + pulseRate);
   }


   public static void main(String[] args)
   {  String name= "";
      int age = 0;
      String ssn = "";
      int diastolic = 0;
      int systolic = 0;
      int temperature = 0;
      int pulseRate = 0;

      System.out.print("Name? ");
      name = Console.in.readLine();
      System.out.print("Age? ");       
      age = Console.in.readInt();
      System.out.print("SSN? ");
      ssn = Console.in.readWord();

      diastolic = diastolicBloodPressure();
      systolic = systolicBloodPressure();
      temperature = thermometer();
      pulseRate = pulse();

      printChart(name, age, ssn, diastolic, systolic, temperature, pulseRate);
   }

   public static int LO = 0; 
   public static int HI = 200;
}
/* Draw a stick figure that waves its right arm
*/

import ccj.*;

public class Wave extends GraphicsApplet
{  public void run()
   {  Point upperTorso = new Point(0.0, 5.0);
      Point lowerTorso = new Point(0.0, -3.0);
      Point lowerLeftArm = new Point(0.0, 4.0);
      Point upperLeftArm = new Point(-4.0, 3.0);
      Point lowerRightArm = new Point(0.0, 4.0);
      Point upperRightArm = new Point(4.0, 7.0);    
      Point upperLeftLeg = new Point(0.0, -3.0);
      Point lowerLeftLeg = new Point(-5.0, -9.0);    
      Point upperRightLeg = new Point(0.0, -3.0);
      Point lowerRightLeg = new Point(5.0, -9.0);        
    
      for (int i = 1; i <= 100; i++)
      {  upperRightArm = new Point(3.0, 8.0);
         clearWindow();
         new Circle(new Point(0.0,6.0), 1.0).draw();
         new Line(upperTorso, lowerTorso).draw();
         new Line(upperLeftArm, lowerLeftArm).draw();
         new Line(upperRightArm, lowerRightArm).draw();
         new Line(upperLeftLeg, lowerLeftLeg).draw();
         new Line(upperRightLeg, lowerRightLeg).draw();

         upperRightArm = new Point(4.0, 7.0);
         clearWindow();
         new Circle(new Point(0.0,6.0), 1.0).draw();
         new Line(upperTorso, lowerTorso).draw();
         new Line(upperLeftArm, lowerLeftArm).draw();
         new Line(upperRightArm, lowerRightArm).draw();
         new Line(upperLeftLeg, lowerLeftLeg).draw();
         new Line(upperRightLeg, lowerRightLeg).draw();
       }
   } 
}   

R2. Interfaces

An object is constructed and it's data accessed and modified only through the use of a class' methods. These functions define a 'black box' interface to the member data. Provide a constructor and the accessors and mutators necessary to perform the identified services from within a main function using the classes you defined in the of three preceeding examples.

Optimal Ticket Price

Patient Vital Sign Graph

Waving Stick Figure


R3. Encapsulation

Consider the following class declaration.

class Product
{  public Product(String n, double price);
   public void increasePrice(double percentage);
   public int getPrice();
   public int quantity;
   private String name;
   private double price;
}

class Product fails to effectively encapsulate a data member, thereby risking a runtime error due to corrupted data. Locate the problem(s) and propose a solution.

One of the data mambers is properly encapsulated but its value cannot be detected. What is it, and what method might be added later that might use it?


P1. Methods

Suppose that the Product class is going to be expanded for use in an inventory control system. Declare data fields, accessors and mutators which will keep track of the number of units of type Product that have been sold.

class Product
{  public Product();
   public Product(String n, double price);
   public void increasePrice(double percentage);
   public int getPrice();
   public void print()
   /*
      Your work goes here.
   */
   private String name;
   private double price;
   /*
      ... and here.
   */
}

Write a program that tests the features of your Product class.

Suppose that management now wants to automate the inventory control system. You'll need to declare or modify data members, constructors, accessors and mutators to expand the Product class to reorder more of itself when needed. Specifically, have every Product know its minimum supply, minInventory, and the amount to order reorderQty if the supply gets too low.

Enhance your Product class to fulfill the new requirements. Write a program that tests the new feature. Insert print statements into your code to provide a trace of your program's execution of a series of sales and a subsequent reorder.


P2. Object Construction

In each of the following examples, provide a constructor and a print function for the specified object.

/* Prints out generic greeting from vacation spot of choice 
 */
class Postcard
{  . . .
   public void print() 
   {   System.out.println("Dear " + toString);
       System.out.println("Weather's great, Wish you were here !");
       System.out.println("See you soon,");
       System.out.println(fromString);
   }
}

Write a program that constructs a postcard object and calls the print method.

class BankAccount
/* Simulate opening an new account at Grand Cayman 
   Savings and Loan.
*/            
{  public BankAccount(String newName, double initialBalance)
   {  /* your work here */  }

   public void printBalance()
   {  /* your work here */  }
                                       
   private int accountNumber; /* randomly assigned integer */
   private String last;      /* first, middle and last names extracted from input name */
   private String middle;
   private String first;
   private double balance;
}

Write a program that constructs a BankAccount object and calls the print method.


P3. Using object oriented design to build complex programs

The objects we've used are particular instances of generally defined classes. For example, Harry Hacker is a particular instance of the Employee class who happened to get a raise last year, whereas another employee might not have gotten one.

Classes in Java can be thought of in terms of nouns and verbs, where a noun is something and a verb does something. Frequently, the noun is stored as data and the verbs are represented by methods which access and mutate the data. It is also not unusual for classes to contain objects of other classes as data. Several classes can also be combined into a larger program to perform more complex tasks, for example, simulating a real world situation.

Earlier in this lab, you developed Account and Product classes. These are either suitable or extensible for use in many business transactions, for example a vending machine. Suppose now that you are running a company that supplies vending machines.

Your customers are other companies or organizations who place the machines on their premises. Your customers pay you a rental charge and buy the drinks from you at a wholesale price. They get to keep the money that their customers, that is, the users of the vending machines, pay for the drinks.

Once a week, a maintenance person comes along to restock the machine. At that time, the machine's account gets credited for the retail price of the purchased drinks and it gets debited for the weekly rental charge and the wholesale price of the restocked drinks.

In your program, you can choose to implement a graphical user interface and accept mouse clicks, or a text-based interface where you prompt the user what button to press. (You should assume that a user who buys a drink automatically inserts the correct change.) Also assume that the "Restock" button is only pressed by an authorized person (perhaps it is operated by a key).

Vending  Machine

Finding Interfaces

Supply the interfaces for VendingMachine, Product and Account classes to simulate this business situation.

Implementing Interfaces

Implement the interfaces you designed and combine them into a simulation program. Your program should simulate two machines.


Don't forget to send your answers when you're finished.