We wish to generate a class that embodies the characteristics of a two-dimensional point.
// Point.java
// Definition of class Point (version 1)
import java.awt.Graphics;
/**
* Point describes a two-dimensional point.
*/
public class Point
{
static final double SCALE = 100;
private double x, y; // coordinates of the Point
// No-argument constructor
public Point() { setPoint( 0, 0 ); }
// Constructor
public Point( double a, double b ) { setPoint( a, b ); }
// Set x and y coordinates of Point
public void setPoint( double a, double b )
{
x = a;
y = b;
}
// get x coordinate
public double getX() { return x; }
// get y coordinate
public double getY() { return y; }
public void draw(Graphics g)
{
int nx = (int) (x*SCALE);
int ny = (int) (y*SCALE);
g.fillOval(nx-5,ny-5,11,11);
}
// convert the point into a String representation
public String toString()
{ return " (" + x + ", " + y + ")"; }
}
Class Point contains
draw
Object.toString()
// Test1.java
import java.awt.*;
import javax.swing.*;
public class Test extends JApplet {
Point pt[];
public void init()
{
pt = new Point[3];
pt[0] = new Point(0.1,0.1);
pt[1] = new Point(0.5, 0.8);
pt[2] = new Point(0.8,0.1);
System.out.println("Points:" + pt[0] + pt[1] + pt[2]);
}
public void paint(Graphics g)
{
for (int i=0; i<pt.length; i++) pt[i].draw(g);
}
}
The test applet
Maintained by John
Loomis, last updated 6 June 2000