CPSC 124: Lab 5
Introduction to Classes


JAVA IS "OBJECT ORIENTED." This means that programs are written by creating classes and using them to make objects. Each object has its own data and behaviors, which are determined by the class to which it belongs. When you are trying to write an object-oriented program, you should look for conceptual "objects" in the problem you are trying to solve, and you should represent those objects as software objects in your program. In this way, the structure of the program can reflect the real-world structure of the problem it is supposed to solve.

In this lab, you will work with classes and objects in two ways. In Part 1, you will write a simple class that represents statistical information about a set of numbers. In Part 2, you will use some the predefined classes from the AWT to write an Applet.

Note: I have upgraded CodeWarrior from version 9 to version 10. Version 10 has some significant improvements in its implementation of Java. If you open a project file from version 9 using the new version of CodeWarrior, you'll be asked if you want to "convert the project." Just say yes. (I've already upgraded all the project folders on the Math/CS Server.)


Part 1: Making a Class

For this part of the lab, you will write a class. You should start with a new copy of the "Java Console Ap Starter" for the file server. Create a new file containing your class, and add it to the project. For your main program, you can use the sample main() routine, given below. The only thing you need to turn in is a print-out of the class file that you write. It should, of course, be properly commented, indented, etc.

Every object is constructed based on some class. The object is said to be a member or instance of that class. The class specifies what types of data the object will contains and what methods are available for manipulating that data.

Recall that a class is just a list of variable declarations and method definitions. The variables and methods that are not declared to be static will become part of each object that is constructed based on the class.

For the first part of this class, you will write a class named StatCalc that can be used for statistical analysis of a set of numbers. The idea is that you can create an object of type StatCalc and then "feed" the numbers into that object one-by-one. The object can then be queried to determine three statistical data about the numbers: the mean (that is, the average) of the numbers, the standard deviation, and the count of the numbers.

Here is an example of a main program that uses the StatCalc class. (If you are smart, you will just cut-and-paste this example from Netscape into your program!)

        public class DoStats {
           public static void main(String[] args) {
              Console console = new Console();
              StatCalc stats = new StatCalc();  // create a StatCalc object
              console.putln("Enter your data, one number on each line.");
              console.putln("Enter any negative number to end:");
              double num;
              do {
                  console.put("? ");
                  num = console.getlnDouble();
                  if (num >= 0)
                     stats.enter(num);  // enter num into the StatCalc object
              } while (num >= 0);
              console.putln();
              console.putln("Here are some statistics about your numbers:");
              console.putln();
              console.putln("Number of data entries: " + stats.getCount());
              console.putln("         Average value: " + stats.getMean());
              console.putln("    Standard Deviation: " + stats.getSD());
              console.putln();
              console.close();
           }
        }

Your assignment for this part of the lab is to write the Class StatCalc with instance methods enter(), getCount(), getMean(), and getSD(). It is not necessary for objects of type StatCalc to store a list of all the numbers entered. All the information you need can be stored in three instance variables:

(These should be private instance variables to protect them from malicious change by entities outside the class.) Your enter() method should simply make the appropriate changes to count, sum, and sumSquares. (That is, it should add one to count, add the number to sum, and add the square of the number to sumSquares.) The getCount() simply returns the value of count. The getMean() returns the average value, which is computed by dividing the sum by the count. The getSD() method returns the so-called "population standard deviation" of the numbers, which is computed as: the square root of (1.0/count) * (sumSquares - count * average2). (The standard deviation contains information about how "spread out" the data is around the average value.)

By the way, you might take a closer look at CodeWarrior 10 editing windows. In particular, you'll find some useful buttons at the top left of the windows, as shown in the example. When you click on any of these buttons and hold the mouse down, you get a pop-up menu. The button on the left, labeled "h", is a list of classes used by the class you are editing. By selecting a class from that list, you can open the file where that class is defined. The next button, labeled "{}", is even more useful. It contains a list of the methods defined in the file you are editing. Selecting a method from this list will take you directly to that method. This is a very easy way to navigate your way around a long class file. You might try out this button on your StatCalc class, to see how it works.


Part 2: Your First Applet

You probably think of an applet as a small Java program that runs in a rectangle on a page in a Web browser. Technically, though, an applet is an object, in the sense of object-oriented programming. It does not have a main() routine. Instead, it has methods for responding to certain events that can occur in a graphical user interface. Events include things like mouse clicks, key presses, and selecting an item from a menu. The "system" -- for example, the Web browser in which the applet is running -- detects the events and calls the appropriate method in the applet so that the applet can respond to the event.

To program an applet, you have to write a class to define the applet's behavior. The class will be used by the system to create an applet object, and it's the applet object that actually appears on the screen. (In fact, you could have several instances of the same applet on a Web page. Each instance is a separate object, but all the instances belong to the same class.) Since an applet is an object, its behavior is defined by instance methods rather than static methods, and any data used by the applet should be stored in instance variables.

The definition of an applet class generally takes the form:

      import java.awt.*;   // use java's GUI classes
      import java.applet.Applet;  // use the basic applet class
      
      class MyApplet extends Applet {
          .   
          .   // declarations of instance variables and methods
          .
      }

(A new applet class "extends" an existing class named Applet. This means that much of the behavior of the new applet class is inherited from the basic Applet class, and therefore does not have to be re-written. This idea of inheritance is one of the most fundamental concepts in object-oriented programming.)

There are several standard methods that you can include in an applet to react to various events. The ones that you will use in this lab are:

        public void init() {  // This is called when the applet is
            .                 // first created, to give it a chance
            .                 // to set itself up and initialize its
            .                 // instance variables.
        }
        
        public void paint(Graphics g) {
            . // This is called when the applet needs to
            . // be redrawn, for example because it was hidden
            . // behind another window, or because some other
            . // method has called the repaint() method.
        }
        
        public boolean mouseDown(Event evt, int x, int y) {
             .  // This is called when the user clicks the mouse at the
             .  // point (x,y).  (0,0) is at the top left of the applet;
             .  // x measures pixels from left to right; and y measures
             .  // pixels from top to bottom.  You can ignore the Event
             .  // parameter, but it has to be there when you write the method.
            return true;  // Return true to system, to indicate that the
        }                 //     event has been handled.
         
        public boolean mouseDrag(Event evt, int x, int y) {
             .  // This is called when the user moves the mouse while
             .  // holding down the mouse button.  (x,y) gives the new
             .  // location of the mouse.
            return true;  // Return true to system, to indicate that the
        }                 //     event has been handled.
        
        public boolean action(Event evt, Object arg) {
             .  // Called when the user performs certain actions,
             .  // such as clicking on a button or selecting an item
             .  // from a pop-up menu.
        }

You must understand that all these routines are called by the system at the appropriate times. You define the method to say what happens when the event occurs. You will hardly ever call these routines yourself.

For this part of the lab, you should use the folder "Lab 5 Applet" from the file server. Copy the folder onto your computer, open the project file, and look at the file, "FirstApplet.java". This file defines a simple applet. You should read the comments on the applet and try running it. (Note that when you "run" an applet in CodeWarrior, it looks for an HTML file in the project. The HTML file defines which applet is to be run and how big its window is to be. You'll learn more about this in future labs. For now, just don't change the name of the applet class or any of the settings in the CodeWarrior Preferences.)

You will find that the Applet lets you move a little red square around in the applet by clicking with the mouse. It also lets you make the square bigger by clicking on a button.

Your assignment, after you have tried the sample applet is to improve it in two ways:

Turn in a print out of the class file for your applet. Since your assignments are beginning to exceed my ability to check your programs just by reading them, I would also like a copy of your entire CodeWarrior project so that I can try running your applet if necessary. Please name your project folder with your last name and copy it into "Eck's Drop Box" on the file server. (If you have a lab partner, please put both last names on the folder.)


The CodeWarrior Debugger

As a last exercise, which you should do on your own time, if necessary, you should start getting acquainted with the CodeWarrior "debugger". There is no exercise to turn in for this part of the lab. However, as you begin to write more complicated programs, you will find the debugger more and more useful. It's a good idea to start working with it now.

A "debugger" is used as an aid in finding and eliminating bugs in a program. You can use the debugger to stop your program in the middle of its execution and inspect the values of the variables. You can also step through the program one instruction at a time and watch what happens in detail.

The CodeWarrior debugger is reasonably easy to use. Just choose the "Enable Debugger" command from the Project menu. Then the "Run" command will change to "debug". When you choose this Debug command, both your program and the debugger will be started up. You'll see a window that looks like this (I've labeled some of the important features):

(Main Codewarrior Debugging Window)

Your program is displayed in the bottom part of the window. You should set one or more breakpoints in your program. Then click on the "Go" button to begin executing the program. As the program is executed, when the computer encounters a breakpoint, it will stop executing and you will have a chance to look at the variables. Then you can either click on the "Go" button to resume execution of the program, or click on the "Step" button to execute just the next instruction. (The debugger has a lot of other advanced features. You can learn about them as you become more experienced with it.)

Often you want to set a breakpoint in a file other than your main program file. The debugger has another window that can be used to view other classes and to set breakpoints in them. This second window looks like this (Again, I've labeled some of the parts of the window):

(CodeWarrior Debugger Classes Window)

You should try using the debugger to catch your StatCalc class in the act of entering a number into the data set. Open your StatCalc project. Turn on the debugger with the Enable Debugger command. Use the Debug command to run the program. Set the debugger's second window to set a breakpoint in the enter() method of your class. Then click on the Go button. When the program stops at the breakpoint, try stepping through the method to see how it works.

You should keep in mind that the debugger is itself a very complicated program. When you run a Java program with debugging enabled, there are actually four different programs involved: the program you wrote, the Java interpreter, the CodeWarrior IDE, and the debugger. Each of these programs can have its own windows, so the screen can get pretty crowded. Just try not to panic!

By the way, after you have enabled the debugger, if you want to simply run your program without using the debugger, just hold down the option and select the "Run" command from the Project menu.


[ Lab Index | Online Notes ]