Designing Java Classes (part 2)

Now we want generate a class that embodies the characteristics of a two-dimensional line segment or parametric line. This object includes instances of class Point objects. We have also modified the code in Point

// Line.java
// Definition of class Line (version 1)
import java.awt.Graphics; 

/**
*  Line describes a two-dimensional line.
*
*     The line is defined by parametric equations
*
*          x(u) = pa.x * (1-u) + pb.x * u;
*          y(u) = pa.y * (1-u) + pb.y * u;
*/


public class Line {
	public Point pa = new Point();
	public Point pb = new Point();

	public Line() { setLine(0,0,0,0); }

	public Line(Point a, Point b) { setLine(a.x,a.y,b.x,b.y); }

	public void setLine(double x1, double y1, double x2, double y2)
	{
		pa.setPoint(x1,y1);
		pb.setPoint(x2,y2);
	}

	public Point getPoint(double u)
	{
		double up = 1.0-u;
		double x = pa.x * up + pb.x * u;
		double y = pa.y * up + pb.y * u;
		return new Point(x,y);
	}

	public void draw(Graphics g)
	{
		g.drawLine(pa.nX(),pa.nY(),pb.nX(),pb.nY());
	}
}

Test Applet

// Test2.java
import java.awt.*;
import javax.swing.*;

public class Test extends JApplet {
	Point pt[];
	Line seg[];

	public void init()
	{
		pt = new Point[3];
		pt[0] = new Point(0.1,0.1);
		pt[1] = new Point(0.5, 0.8);
		// use chainable methods setX() and setY()
		pt[2] = new Point().setX(0.8).setY(0.1);
		seg = new Line[3];
		seg[0] = new Line(pt[0],pt[1]);
		seg[1] = new Line(pt[1],pt[2]);
		seg[2] = new Line(pt[2],pt[0]);
	}
	public void paint(Graphics g)
	{
		for (int i=0; i<seg.length; i++) seg[i].draw(g);
	}
}

Point class

// Point.java
// Definition of class Point (version 2)
import java.awt.Graphics; 

/**
*  Point describes a two-dimensional point.
*/

public class Point
{
	static final double SCALE = 100;
	public 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 pixel value
	public int nX() { return (int)(x*SCALE); }

	// get y pixel value
	public int nY() { return (int)(y*SCALE); }

	//  set X coordinate
	public Point setX(double a)
	{
		x = a;
		return this;
	}

	// set Y coordinate
	public Point setY(double b)
	{
		y = b;
		return this;
	}

	// offset (translate) point by the amount (tx, ty)
	public void offset(double tx, double ty)
	{
		x += tx;
		y += ty;
	}

	public void draw(Graphics g)
	{
		int nx = nX();
		int ny = nY();
		g.fillOval(nx-5,ny-5,11,11);
	}   

   // convert the point into a String representation
   public String toString()
      { return " (" + x + ", " + y + ")"; }
}


Maintained by John Loomis, last updated 6 June 2000