Designing and Implementing a class

Then testing the class

 

Step 1: The specifications

      Find out what you are asked to do with an object of the class (i.e. start with what needs to be done)

      Suppose you are asked to implement a CashRegister class that will be used for customers in a store

      Make a list, in plain English, of the operations that an object of the class should carry out:

      Think of the object of the class as the financial record for a customer in the store

    Ring up the price for each item a customer buys

    Enter the amount of payment (may be more than one payment)

    Calculate the amount of change due to the customer

 

Step 2: Specify the public interface

      How will the user of the class (the client) want to use it?

    In your mind, you need to separate the writer of the class from the user or client of the class

      Turn the list in Step 1 into a set of methods the client can call

    Each method must have a name, a return type, and arguments

    Give some thought to the names; they should reflect what the method will do

    Information flow from/to user of class

    Decide what information must come from the user (arguments),

     what information must be returned to the user (return type)

 

Step 3: Determine the instance variables

      What information needs to be kept for each object?

   In this case, an object is the financial record of one customer

      Decide on the data type for each instance variables

 

Step 4: Implement the methods

      This includes a constructor and the methods we have designed

   I also included a toString method to make it easier to test the class

      Mutators and accessors if they are needed

      The instance variables should be private, while the methods should be public

 

Step 5:  Test your class

      Usually this is done in a separate class with a main method

      The tester is often called the client or the driver

      Every method should be called, to be sure it is doing what it should

      If your class has a toString method, outputting the entire object is easier.

 

Formatting floats with printf

      printf(%f) lets you specify two things

   The width of the field

   The number of digits after the decimal point (called the precision)

 

 

Numbers in the computer

Primitive types

Four integers type

byte -- 8 bit signed integral value

short -- 16-bit signed

int-- 32 bit signed (most commonly used)

long -- 64 bits

Floats

float – 32 bits (6 to 7 significant decimal digits , exponent to 38)

     double – 64 bits (15 significant  decimal digits, exponent to 308)
Floats are stored in the computer differently than integers

    Floating point calculations are much slower than integer calculations

 

Problems with numbers

      Overflow with ints

      Rounding errors with floats or doubles