Lab 4: Javdoc





The Java API Documentation

If msg is an instance of the Java String class, then the call:

msg.trim(); returns a new string that is identical to msg, except with leading and trailing white space characters removed.

Sometimes the vast quantity of obscure Java methods like this one can be depressing. How can anyone be expected to know all of the methods for all of the classes? Relax. No one does. But a good programmer is proficient at sniffing through reams of documentation to come up with the perfect method for the situationj at hand.

Fortunately, Sun has thought a lot about Java documentation. Every class in every package has a web page devoted exclusively to the public methods and fields of that class. Furthermore, each reference to another class is a link to the corresponding web page. The collection of all Java web pages can be found on the Web at:

http://java.sun.com/j2se/1.3/docs/api/index.html Alternatively, programmers can download the entire web site and install it on their own machines for faster access.

Problem 1: Write a Java program to calculate the number of seconds that have elapsed since the stroke of midnight in London on New Years Eve, 1970. Your program should be no more than a few lines long. Is there some pre-defined method you can use to help. What class does it belong to? What package does the class belong to?

Javadoc: The Java API Documentation Generator

Generally speaking, there are two types of comments: interface and implementation. Implementation comments describe which algorithm a method uses or how to interpret the private fields of a class. This information is useful for programmers who must maintain or debug the class. Interface comments describe what task a method performs or how to interpret instances of a class. These types of comments are useful for clients- programmers who must use the class.

javadoc is a tool that comes with the compiler, virtual machine, and other tools bundled in the Java development kit. Given one or more .java files as input, javadoc extracts all of the interface comments and uses them to generate a collection of web pages formatted like the pages that describe the pre-defined JDK classes. javadoc recognizes interface comments by their distinctive format:

/**
* Summary sentence.
*
* @tag blah, blah, blah
* @tag yadah, yadah, yadah
* @tag etc, etc, etc
*/
where @tag is one of several predefined javadoc tags that preface descriptions of parameters, return values, exceptions thrown, version numbers, author names, etc.

The following examples involve the declarations of two associated classes: Point and Box. Instances of the Box class represent rectangles in an integer plane with an upside down y axis. The important fields of a Box are its integer height and width as well as its upper left corner, which is a point:

Here are some uncommented declarations from Point.java and Box.java respectively:

public class Point {
   public int xc, yc;
   // etc.
}

public class Box {
   protected int height = 0, width = 0;
   protected Point topLeft;
   public void move(Point p) { topLeft = p; }
   public void resize(int h, int w) { height = h; width = w; }
   // etc.
}

Commenting Classes

Class (and interface) comments begin with a summary sentence describing what instances of the class represent. The summary sentence is terminated by a tag or by a period followed by a blank, tab, or newline character.

A summary is followed by a blank line followed by the names of the authors and the version number. Java provides special @author and @version tags that preface this information.

For example, here is a class comment for our Point class:

/**
* Instances of the Point class represent points
* in an integer plane.
*
* @author Bart Simpson
* @version 1.0
*/
public class Point {
   // etc.
}
To write more complex class comments programmers can include HTML elements such as lists, links, images, code, line breaks, paragraphs, and non-breaking spaces.

For example, the comment for our Box class begins with a summary that is several paragraphs long and contains a Java expression. To keep javadoc from prematurely terminating the summary, each period is immediately followed by an HTML tag. Periods that end sentences are followed by paragraph tags, periods that don't end paragraphs are followed by non-breaking space tags (&nbsp). We wanted to control the formatting of the Java expression, so we bracketed it with HTML code tags. To force the indentation we added several HTML non-breaking space tags just before the code segment. It's important to remember that browsers ignore the tabs, blank lines, and spaces we insert into our HTML.

/**
* Instances of the Box class represent rectangles
* in the first quadrant of an integer plane with
* an inverted y axis.<p>
*
* If p and q are two points in such a plane with
* the same x coordinates but with the y coordinate
* of p larger than the y coordinate of q: <p>
*
* &nbsp;&nbsp;&nbsp
* <code>(p.xc == q.xc && p.yc > q.yc)</code><p>
*
* then p is "below" q.&nbsp;In particular, the origin of this
* type of plane is always located at the top left corner
* of the page or window.<p>
*
* This can be confusing, because it means the y coordinate
* of the top left coordinate of a Box is smaller than the
* y coordinate of its center point or its bottom right corner.<p>
*
* This type of coordinate system is chosen for compatability
* with the coordinate system used by the Graphics class
* in Java's awt package.
*
* @author Bart Simpson
* @version 1.0
*
* @see <a href="docs/api/java/awt/Graphics.html">Graphics</a>
*/
public class Box {
   // etc.
}
Javadoc also provides a @see tag so programmers can insert links to other pages. In our box example we provide users with a link to the page that documents Java's Graphics class.

Here's what the class comment looks like in a browser:

public class Box
extends java.lang.Object

Instances of the Box class represent rectangles in the first quadrant of an integer plane with an inverted y axis.

If p and q are two points in such a plane with the same x coordinates but with the y coordinate of p larger than the y coordinate of q:

(p.xc == q.xc && p.yc > q.yc)

then p is "below" q. In particular, the origin of this type of plane is always located at the top left corner of the page or window.

This can be confusing, because it means the y coordinate of the top left coordinate of a Box is smaller than the y coordinate of its center point or its bottom right corner.

This type of coordinate system is chosen for compatability with the coordinate system used by the Graphics class in Java's awt package.

Version:
1.0
Author:
Bart Simpson
See Also:
Graphics

Commenting Fields

Interface documentation doesn't mention private fields or methods, because they are part of the implementation of a class. However, public and protected field comments must include a summary phrase or sentence:

public class Point {

   /**
    * The x-coordinate of this Point.
    */
   public int xc;

   /**
    * The y-coordinate of this Point.
    */
   public int yc;

   // etc.
}

Notice the repeated use of the phrase "this Point". This is the javadoc convention for referring to the implicit parameter: the word this followed by the class name.

Of course protected methods and fields are part of the interface seen by class extenders, so they too must be documented. For example, the Box class will grant access to its height, width, and topLeft fields to the classes that extend it:

public class Box {

   /**
    * The height of this Box.
    */
   protected int height = 0;

   /**
    * The width of this Box.
    */
   protected int width = 0;

   /**
    * The top left corner of this Box.
    */
   protected Point topLeft;

   // etc.
}

Commenting Methods

Like a class comment, a method comment begins with a summary sentence or phrase. However, the summary of a method comment is followed by one @param tag describing each parameter, and a @return tag describing how clients should interpret the return type. Often, this is just a repeat of the summary, but that's okay. Constructors and void methods aren't required to have @return tags.

For example, here is the method tag for the Point.equals() method.

/**
* Determines if argument is a Point with the same
* coordinates as this Point.
*
* @param obj any Object
*
* @return <code>true</code> if obj is a Point with
* the same coordinates as this Point;
* <code>false</code> otherwise
*/
public boolean equals(Object obj) {
   if (obj instanceof Point) {
      Point p = (Point) obj; // must downcast
      return (xc == p.xc) && (yc == p.yc);
   } else {
      return false; // no way!
   }
} // equals
Notice that if phrases are used rather than sentences, then there is no terminating period and the phrase begins with a lower case letter. Phrases are separated by semicolons. For example, the description of the return value for the Point.equals() method consists of two phrases.

Here's the method comment for the Point.toString() method:

/**
* Returns the String representation of this Point.
*
* @return the String representation of this Point
*/
public String toString() {
   return "(" + xc + ", " + yc + ")";
}
javadoc also allows programmers to document exceptions thrown by using the @throws or @exceptions tag. For example, the Box.move() method throws an exception if the user tries to move its implicit parameter out of the first quadrant: /**
* sets the top left corner of this Box to the
* specified Point; displays this Box
*
* @param p the new top left corner of this Box
*
* @throws Exception if p is not in the first quadrant
*/
public void move(Point p) throws Exception {
   if (p.xc < 0 || p.yc < 0)
      throw new Exception("position must be in first quadrant");
   topLeft = p;
   display(); // print box size & position
}
The Box.resize() method throws an exception if the user specifies a negative height or width: /**
* sets the height and width of this Box to the
* specified values; displays this Box
*
* @param h the new height of this Box
* @param w the new width of this Box
*
* @throws Exception if height or width is negative
*/
public void resize(int h, int w) throws Exception {
   if (h < 0 || w < 0)
      throw new Exception("height & width must be >= 0");
   height = h;
   width = w;
   display(); // print box size & position
}
Even ordinary getter and setter methods should have method comments: /**
* returns the height of this Box
*
* @return the height of this Box
*/
public int getHeight() { return height; }

/**
* computes the area of this Box
*
* @return the area of this Box
*/
public int getArea() { return height * width; }

Here's what the method documents for Box.resize() and Box.getSize() when they are displayed by a browser: resize

public void resize(int h,
int w)
throws java.lang.Exception

sets the height and width of this Box to the specified values;
displays this Box
Parameters:
h - the new height of this Box
w - the new width of this Box
Throws:
java.lang.Exception - if height or width is negative

getHeight

public int getHeight()

returns the height of this Box
Returns:
the height of this Box

Commenting Constructors

Constructor comments are a special case of method comments that don't include @return tags:

   /**
    * Constructs and initializes this Point with the
    * specified x and y coordinates.
    *
    * @param x the x coordinate
    * @param y the y coordinate
    */
   public Point(int x, int y) {
      xc = x;
      yc = y;
   }

   /**
    * Constructs and initializes this Point with x & y
    * coordinates equal to 0.
    */
   public Point() { xc = yc = 0; }

Problem 2: Complete the declarations and comments for the Point and Box classes. Besides the methods discussed, your Box class should include the following methods: public int getWidth() { ... }
public int getPerimeter() { ... }
public Point getTopLeft() { ... }
public Point getBottomRight() { ... }
public Point getCenter() { ... }
public Point getTopLeft() { ... }
public void display() { ... }
public static void Point.main(String[] args) { ... }
The Box.display() method prints the top left, center, bottom right, height, width, area, and perimeter of its implicit parameter. The Box.main() method is a test harness that creates, moves, and resizes a couple of boxes.

Problem 3: Create and document a Label class that extends the Box class. A label is a box that contains a message:

class Label extends Box {
   private String text; // the message
   public Label(String msg) throws Exception { ... }
   public String getText() { ... }
   public void setText(String msg) { ... }
   public void display() { ... }
   public static void main(String[] args) { ... }
   // etc.
}
The height of a label is always three. The width is two more than the length of the message. The constructor calls the constructor of its super class, Box. If this constructor throws an exception, then so does the Label constructor.

The javadoc Command

The javadoc command is typed at a command console prompt, together with options and a list of .java files:

d:\jlab> javadoc -version -author Point.java Box.java Label.java Problem 4: Generate documentation for the Point, Box, and Label files. Place all of the HTML and style sheet files onto a floppy, and turn it in.