Polygon Contract

A instance of Java's polygon class is a sequence of (x,y) coordinates that defines the sides of a geometric polygon. Each pair of consecutive coordinates in the sequence defines one side of the polygon. In order for the polygon to be closed, the final coordinate must be the same as the first.

A particular polygon can be constructed by creating an empty Polygon (via new Polygon()) and using the addPoint method to add points to this polygon. For example, here is code for creating a triangle named tri with coordinates (30, 10), (30, 20), and (20, 15):

    Polygon tri = new Polygon();
    tri.addPoint(30,10);
    tri.addPoint(30,20);
    tri.addPoint(20,15);
    tri.addPoint(30,10);

Below is a simple contract for the Polygon class. The Polygon class actually implements more constructors and methods than are described here. The full list of methods can be found in the Java API for the class java.awt.Polygon.


Index for the Polygon Class

Constructors:

Methods:

Instance Variables:


Constructors of the Polygon Class


Polygon

public Polygon()

Creates an empty polygon.


Methods of the Polygon Class


addPoint

public void addPoint(int x, int y)

Appends the point (x,y) to this polygon.
If an operation that calculates the bounding box of this polygon (getBoundingBox or inside has already been performed, this method updates the bounding box.

Parameters:
x - the x coordinate of the point
y - the y coordinate of the point


getBoundingBox

public Rectangle getBoundingBox()

Returns:
the smallest rectangle than contains this polygon


inside

public boolean inside(int x, int y)

Determines if the specified point is inside this polygon. This method uses an even-odd insideness rule (also known as an "alternating rule") to determine whether the point (x,y) is inside this polygon.
Parameters:
x - the xcoordinate of the point to be tested
y - the y coordinate of the point to be tested
Returns:
true if the point (x,y) is inside this polygon; false otherwise.



Instance Variables of the Polygon Class


npoints

public int npoints

The total number of points in the polygon.



Franklyn Turbak adapted this page from the
Java API Document (HTML generated by dkramer on April 22, 1996)
Copyright © 1996 Sun Microsystems, Inc. All rights reserved
Please send any comments or corrections to
doug.kramer@sun.com