Docstoc

LAB02

Document Sample
LAB02 Powered By Docstoc
					                           LAB #02 polymorphism and packages

Objectives:
To gain experience with:
    polymorphism
    packages


1. Polymorphism
Example 1:
The following applet makes use of the family of classes discussed in Lab01 and using
polymorphism draws random shapes. Trace the code and make sure you understand
everything about it.

   import java.applet.Applet;
   import java.awt.Graphics;
   import java.awt.Color;
   import java.util.Random;

   // This applet creates and draws multiple random shapes.
   public class RandomDraw extends Applet {
     final int DIMENSION_MAX = 300; //maximum value of a dimension
     final int NUM_SHAPES = 2; //different possible shapes(line & rectangle)
     final int LINE = 1; //label for Line shape
     final int RECTANGLE = 2; //label for Rectangle shape
     final int MAX_SHAPE = 20;
     Shape[] shapes = new Shape[MAX_SHAPE];

   // Creates and stores multiple shapes.
     public void init() {
       int x1,y1;
       Random random=new Random();
       Color color;
       for (int index = 0; index < MAX_SHAPE; index++) {
          int i=random.nextInt(NUM_SHAPES)+1;
          x1 = random.nextInt(DIMENSION_MAX);
          y1 = random.nextInt(DIMENSION_MAX);
          color=new Color (random.nextFloat(),random.nextFloat(),random.nextFloat());

         switch (i) {
           case LINE:
             int x2 = random.nextInt(DIMENSION_MAX);
             int y2 = random.nextInt(DIMENSION_MAX);
           shapes[index] = new Line (color, x1, y1, x2, y2);
           break;
         case RECTANGLE:
         default:
           int width = random.nextInt(DIMENSION_MAX);
           int height = random.nextInt(DIMENSION_MAX);
           shapes[index] = new Rectangle (color, x1, y1, width, height);
           break;
      } // switch
   } // for
 }// method init

// Draws all of the shapes on the applet.
  public void paint (Graphics g) {
    for (int index = 0; index < MAX_SHAPE; index++) {
         shapes[index].draw (g);
    } // for
  } // method paint
} // class RandomDraw
2. Java Packages

   A Java package is a collection of sub-packages and/or classes (compilation units).
   The classes in a package may or may not be related by inheritance.
   A package is used to group similar and interdependent classes together.
   The Java API is composed of multiple packages.
   The import statement is used to assert that a particular program will use classes from a
   particular package.
   A programmer can define a package and add classes to it.
   The package statement is used to specify that all classes defined in a file belong to a
   particular package.
   The syntax of the package statement is:
                                       package package-name;
   The package statement must be located at the top of a file, and there can be only one package
   statement per file.

3. Organizing our classes into Packages
   In this course, throughout this semester, we shall be organizing the classes we develop into
   related packages. You are expected to create a directory structure similar to the one in
   Lecture slide number 2 where you will be storing your classes.
   You should create this structure in both your network directory (z-drive), on your floppy and
   on your personal computer if you have one. You will find this very useful by the end of the
   course.
   In addition to the directories on the lecture slides, you are required to create a folder, labs
   with subfolders lab00, lab01, etc. where you will be storing the applications you developed in
   the lab.
   Notice that if you develop a class which is to be used as a type (for creating objects) you
   should store that in its appropriate package. For example, Point class should be stored in the
   graphics package. However, the application/applet that uses the type (e.g. TestPoint) should
   be stored in the package for the lab in which the application/applet is developed.
   The following diagram shows how you may organize your packages.
   Example 2: The following defines a Point class, which is defined in a package called
cs.graphics.


      package cs.graphics;
      public class Point {
           private double x;
           private double y;
           public Point(double x, double y) {
                this.x=x;
                this.y=y;
           }
           public Point() {
                this(0.0, 0.0);
           }
           public double distanceToOrigin() {
                return Math.sqrt((x * x) + (y * y));
           }
           public double distanceToPoint(Point p) {
                return Math.sqrt(((x-p.x)*(x-p.x))+((y-p.y)*(y-p.y)));
           }
           public void moveTo(double x, double y) {
                this.x=x;
                this.y=y;
           }
           public void translate(double dx, double dy) {
                x += dx;
                y += dy;
           }
           public double getX() {
                return x;
           }
           public double getY() {
                return y;
           }
           public String toString() {
                return "("+x+", "+y+")";
           }
           public boolean equals(Point p) {
                return this.x == p.x && this.y == p.y;
           }
Example 3: The following example shows the class ConsoleReader. It is defined in the package
cs.utilities.

      package cs.utilities;

      import java.io.BufferedReader;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.io.IOException;

      /*A class to read strings and numbers from an input stream.
      This class is suitable for beginning Java programmers.
      It constructs the necessary buffered reader,
      handles I/O exceptions, and converts strings to numbers.
      */

      public class ConsoleReader
      {

       /*
      Constructs a console reader from an input stream
      such as System.in
      */
      public ConsoleReader(InputStream inStream)
      { reader = new BufferedReader (new InputStreamReader(inStream));
      }

      /*
      Reads a line of input and converts it into an integer.
      The input line must contain nothing but an integer.
      Not even added white space is allowed.
      */
      public int readInt()
      { String inputString = readLine();
          int n = Integer.parseInt(inputString);
         return n;
      }

      /*
      Reads a line of input and converts it into a floating-
      point number. The input line must contain nothing but
      a number. Not even added white space is allowed.
*/
public double readDouble()
{ String inputString = readLine();
   double x = Double.parseDouble(inputString);
   return x;
}

/*
Reads a line of input. In the (unlikely) event
of an IOException, the program terminates.
*/
public String readLine()
{ String inputLine = "";
 try
   { inputLine = reader.readLine();
   }
   catch(IOException e)
   { System.out.println(e);
      System.exit(1);
   }

    return inputLine;
}

private BufferedReader reader;
}
   Example 4: The following shows how the Point class may be imported along with the
consoleReader
    class

      package cs.labs.lab01;
      import cs.graphics.Point;
      import cs.utilities.ConsoleReader;

      public class TestPoint {
      static ConsoleReader stdin = new ConsoleReader(System.in);

      public static void main(String[] args) throws java.io.IOException{
        double x,y;
        System.out.println("Enter first point: ");
        x=stdin.readDouble();
        y=stdin.readDouble();
        Point p1 = new Point(x,y);
        System.out.println("Enter second point: ");
        x=stdin.readDouble();
        y=stdin.readDouble();
        Point p2 = new Point(x,y);
        System.out.println("Distance of "+p1+ " to origin = "+p1.distanceToOrigin() );
        System.out.println("Distance of "+p2+ " to origin = "+p2.distanceToOrigin() );
        System.out.println("Distance between "+p1+" and "+p2+ " = "+p1.distanceToPoint(p2) );
      }}
                                                           package cs.graphics;


package cs.graphics;




class ConsoleReader ==package cs.utilities;




class TestPoint   ====> package cs.labs.lab01;




                                                 package cs.labs.lab01;
4. Specifying classpath for user-defined packages
   Java tools (compiler, interpreter, etc) automatically detect the location of the standard Java
   packages.
   However, for user-defined packages, the user must specify their locations. This can be done
   in either of two ways:
   1. Using the set PATH command (not recommended): This is used at the DOS prompt
       before using SDK tools to compile and execute programs. The format is:
                      set CLASSPATH=path1;path2...
       where path1, path2, etc are the ROOT folders of the packages.
                     e.g. set CLASSPATH=”z:/”

   2.   Using the classpath option (recommended): This is used as an option to a SDK tool to
        direct it on where to find the user packages. The format is:
                      sdkTool -classpath path1;path2 source or class file.

                e.g. To compile TestPoint.java, we change to its folder and enter the following:
                     javac –classpath “z:/” TestPoint.java

                       To execute TestPoint.java, we execute the following from any folder:
                     java –classpath “z:/” cs.labs.lab00.TestPoint

                        Notice that for execution, we need to give the full name of the class file.

   3.   We can also compile and execute programs that uses user-defined packages from
        within JCreator. To do this, we need to modify the parameter configuration of both the
        Compiler and Run Application as shown below:
Exercises
  1. Create directory structure as mentioned above.




  2. Modify the RandomDraw class so that you include the two classes
     (Ellipse and Square) designed in Lab01.
  3.       Practice with examples 2-4 through jcreator and DOSprompt. Put
     your packages in different directories
  4.    Put classes designed in Lab01 in package cs.graphics and RandomDraw
     in package cs.labs.lab02 and recompile and run your applet

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:51
posted:3/31/2012
language:
pages:10