4a

Advanced Placement

Computer Science Lab

 

 

Classes and Object Oriented Programming

 

 

 

 

Introduction

 

Up until now we have used objects and classes without really explaining their relationship or their usefulness.  Objects in programming are in a fashion like objects in real life.  For instance lets take a relatively simple object like a ball.  Its first characteristic is that it exists or has a state of being.  An object in a program can also have a state of being and when it does it is said to be an instance of the object. Our ball can also have certain data associated with it.  It can have color, diameter, texture, composition, location, etc.  A program object can also have certain data in the form of variables. In each case these data are specific to the instance of the object.  If we were to have another instance of the object, its data might be different and even if it were not it would still be another instance of the object. Also associated with an object are certain behaviors or actions that use the data associated with the object.  In the case of the ball, this could be the velocity with which it can move under different circumstances, how it spins, whether it increases or decreases in size at different pressures, etc.  A program object will have different methods associated with it.  This grouping of data and methods in a computer program is called information hiding or encapsulation.  One major difference between objects in programming and real world objects is that programming objects can be made from things that are not tangible, e.g. a group of error messages.

 

In order to develop an instance of an object in a program, the object first has to be defined.  In Java the way an object is defined is by using a class.  The class and its associated data and methods represent a template or blueprint of the object.  A class can have any number of data declarations and methods each of which is termed a member of that class.  Let’s examine the structure of a class.  The following is an example of a format for a simple class titled Box:

 

 

 

 

 

 

public class Box

{

     private double boxLength;

     private double boxHeight;

     private double boxWidth;

     private String boxColor;

 

 

     //default constructors

     public Box()

     {

     boxLength = 1.0;

     boxHeight = 1.0;

     boxWidth = 1.0;

     boxColor = "white";

     }

 

     //constructor initializes private variables

     public Box(double len, double hgt, double wid, String col)

     {

     boxLength = len;

     boxHeight = hgt;

     boxWidth = wid;

     boxColor = col;

     }//box

 

     //accessor or getter method - returns value of private variable

     public String getColor()

     {

     return boxColor;

     }//getcolor

 

     //mutator method - changes value of private variables

     public void increaseFactor(double fac)

     {

     boxLength = boxLength * fac;

     boxHeight = boxHeight * fac;

     boxWidth = boxWidth * fac;

     }//increaseFactor

 

     //computational method - computes and returns a value

     public double boxVolume()

     {

     double volume;

     volume = boxLength * boxHeight * boxWidth;

     return volume;

     }//boxVolume

 

     //computational method - computes and returns value

     public double boxSurfaceArea()

     {

     double surfaceArea;

     double sur1;

     double sur2;

     double sur3;

     sur1 = boxLength * boxHeight * 2;

     sur2 = boxLength * boxWidth * 2;

     sur3 = boxHeight * boxWidth * 2;

     surfaceArea = sur1 + sur2 + sur3;

     return surfaceArea;

     }//boxSurfaceArea

 

}// Box

 

 

 

 

 

 

 

First of all notice that we declare four private variables with respect to the dimensions and the color of the box.  This means that dimensions cannot be modified by anything outside the class, i.e. we can not write a line of code in another class like:

 

 

Box box1 = new Box();

box1.boxLength = 12.3;

 

 

without getting an error.

 

Now we want to create another program that will use or instantiate the objects that we have developed a template for in the Box class.  We will call this program BoxUser and a listing of the code follows:

 

 

 

 

 

public class BoxUser

{

    

     public static void main(String[] args)

     {

          double length, height, width, volume, surface;

          String color = "red";

    

          //create a default box

          Box box1 = new Box();

    

          //box1.boxLength = 14.7;

    

          length = 12.2;

          height = 3.47;

          width = 5.38;

    

          //create a second box with specified dimensions

          Box box2 = new Box(length, height, width, color);

    

          //create a third box with default values

          Box box3 = new Box();

    

          volume = box1.boxVolume();

          surface = box1.boxSurfaceArea();

          System.out.println ("Default box volume is: " + volume);

          System.out.println ("Default box surface area is: " +         surface);

 

          System.out.println ("Default box color is: " +                box1.getColor());

    

          volume = box2.boxVolume();

          surface = box2.boxSurfaceArea();

          System.out.println ("2nd box volume is: " + volume);

          System.out.println ("2nd box surface area is: " +              surface);

          System.out.println ("2nd box color is: " +                box2.getColor());

    

          //change dimensions of 3rd box by factor of 2.88

          box3.increaseFactor(2.88);

          volume = box3.boxVolume();

          surface = box3.boxSurfaceArea();

          System.out.println ("3rd box volume is: " + volume);

          System.out.println ("3rd box surface area is: " +              surface);

          System.out.println ("3rd box color is: " +                box3.getColor());

         

     }//main

    

}//BoxUser

 

 

 

 

 

 

 

Notice first how we create a box object.  This is very similar to declaring a variable of a primitive type.  The significant change is the use of the keyword new followed by a method of the same name as the class.  The method is called a constructor and is what actually creates the object of the class type.

 

Box box1 = new Box();

 

If you notice we have two methods or constructors in the Box class of the same name.  One has no parameters and the second has four parameters.  The default constructor for an object will have no parameters.  The constructor with the parameters will be used if we supply the parameters of the type and order specified in the second constructor, e.g.:

 

Box boxA = new Box(23.4, 10.7, 2.34, “orange”);

 

This is an example of method overloading.  The compiler figures out which method to use based upon its signature, i.e. its return type and the parameter list.  Note that in constructor methods we do not specify a return type, not even void.

 

Notice how we access the methods of the class.  We use the “dot” operator that designates the hierarchy necessary for BoxUser to find the appropriate method. An example for above is:

 

volume = box1.boxVolume();

 

Remember from the previous exercise that the terms public, private and static are keywords that are the modifiers of variables and methods within a class.  The term public refers to the fact that the variable or method can be referred to outside the class. The term static allows the variable or method to be invoked without creating an instance of the class.  Because the variables in Box are private they can only be modified or accessed from outside the class by public methods inside the class.  While declaring everything to be public would make everything accessible it would defeat the purpose of encapsulation, which is to prevent the inadvertent modification of data related to an object.

 

Note that to retrieve data from a class we use the accessor or getter method.  Convention usually prefaces that names of these methods with the word “get”.

 

public String getColor()

{

return boxColor;

}//getcolor

 

 

 

 

 

 

Procedure

 

A.  Experimenting with Classes

 

1.         Start a new project called BoxUser.  In the BoxUser source code file replace the template code with the code above.  Start a new class called Box.  Replace the template code in the file with the code above in class Box.  Compile both programs and execute BoxUser.  Why is it that you cannot execute Box?

 

2.         Add the following line of code to BoxUser following the instantiation of box1.  

 

box1.boxLength = 14.7;

 

            Recompile.  What happens.  Why?

 

3.         Add the following line of code to Box following the variable declarations.  

 

public static int boxNumber = 12;

 

            Recompile Box.  Add the following line of code to BoxUser at the end of the code.

 

box1.boxLength = 14.7;

 

            Recompile BoxUser.  Do the programs compile?  Why?  What is unique about the way that the number was accessed in Box?  Would this work if static were removed from the declaration?  If public were removed?

 

 

 

 

 

Programming Assignment

 

Write a class named Die that is similar to the Coin class in your text.  The class should have a constructor that rolls the die, and methods which return the value on the face of the die at the end of the roll. 

 

Write a user or client program for your Die class.  This class should instantiate a Die object, and get the results on rolling the die as many times as the user of the programs wishes.  Compare your results with what would be the expected results.  Use the dialog boxes that we have used in previous lab exercises to initiate the program and display the results.

 

Write a second program that also uses the Die class but this time displays the result that occurs when you roll a pair of dice.

 

Turn in a program listing your source code.  Source code should use proper formatting.  Also turn in a copy of your output as in previous assignments.  This can be obtained by running the program and then using AltPrintScreen to copy the window of the output onto the clipboard. Then paste the contents of the clipboard into WordPad and print out the document.  In addition to the source code, the output, also turn in the answer to the questions listed below.